DEV Community

Cover image for Typescript - Tips & Tricks - keyof
Luca Del Puppo for This is Learning

Posted on β€’ Edited on

7 1

Typescript - Tips & Tricks - keyof

Welcome back!
Today I'll talk about the keyof operator.

This operator helps us to extract the object's properties such as Literal-types

type Person = {
  firstName: string;
  surName: string;
  age: number;
  location: string;
};

type PersonKeys = keyof Person; // "firstName" | "surName" | "age" | "location"
Enter fullscreen mode Exit fullscreen mode

This operator can help us to create new methods that should depend of other types; e.g.

function get<T, K extends keyof T>(obj: T, prop: K): T[K] {
  return obj[prop];
}

function set<T, K extends keyof T>(obj: T, prop: K, value: T[K]): void {
  obj[prop] = value;
}
Enter fullscreen mode Exit fullscreen mode

but also to create new types from other types e.g

type ReadOnly<T> = {
  readonly [K in keyof T]: T[K];
};

type ReadOnlyPerson = ReadOnly<Person>
/*
type ReadOnlyPerson = {
    readonly firstName: string;
    readonly surName: string;
    readonly age: number;
    readonly location: string;
}
*/
Enter fullscreen mode Exit fullscreen mode

How we can see this operator is more powerful and it can help us to create new strict type or new strict methods.

That's all for today.
See you soon guys!

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup πŸš€

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

Top comments (0)

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay