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