Typescript - Tips & Tricks - keyof

Welcome back! Today I'll talk about the keyof operator. This operator helps us to extract the...

#typescript #webdev
Luca Del Puppo Luca Del Puppo
Article Series · Part 3 of 21 TypeScript - Tips & Tricks
View full series (21)
  1. #2 Previous
    Literal Types
  2. #3 Reading now
    keyof
  3. #4 Up next
    Union and Intersection
Browse all 21 parts in this series
  1. #1 typeof
  2. #2 Literal Types
  3. #3 keyof Current
  4. #4 Union and Intersection
  5. #5 Overloaded Functions
  6. #6 this parameter
  7. #7 any vs. unknown
  8. #8 Optional modifier
  9. #9 Index Signature
  10. #10 readonly modifier
  11. #11 Readonly Array
  12. #12 Tuple
  13. #13 Non-null assertion operator
  14. #14 Never type
  15. #15 Assert Function
  16. #16 Type Guard
  17. #17 Conditional Type
  18. #18 infer keyword
  19. #19 Mapped Types
  20. #20 Advanced Types
  21. #21 Rest Parameters & Rest Arguments

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"

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;
}

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;
}
*/

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!

Luca Del Puppo

Written by Luca Del Puppo

Run, Code & Learn

AI Native Engineer at Nearform based in Povegliano (TV), Italy. Google Developer Expert in Web Technologies, GitKraken Ambassador, and Codemotion Ambassador.