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 Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)