DEV Community

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

Posted on • Updated on

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!

Top comments (0)