When I started learning about Typescript
, I kept on seeing keyof typeof
which was confusing for me to grasp at that time. This article will provide an understanding of this concept to leverage for Typescript
newbies and people that want to understand this better.
typeof
typeof
behaves differently when called on javascript object and typescript object.
Consider the following object,
const male = { name: 'John Doe', age: 20, location: 'Abuja'}
In javascript
, typeof male
returns an 'object'
but in typescript
, typeof male
returns type { name: string; age: number; location: string;}
const male = { name: 'John Doe', age: 20, location: 'Abuja'}
#javascript
typeof male = 'object'
#typescript
typeof male = type { name: string; age: number; location: string; }
Typescript's typeof
infers the type of the value of each attribute in the object.
keyof
According to the typescript documentation, the keyof
type takes an object type and returns a string or numeric literal union of its keys.
Consider the example below,
type Point = { x: number; y: number };
keyof Point
will return 'x' | 'y'
which is the literal union of the keys in Point type.
keyof typeof
Now, back to our male
object example, let's assume we want to create a Person type with keys restricted to that of the male object. This is where keyof typeof
comes in handy.
type Person = keyof typeof male
type Person = "name" | "age" | "location"
In conclusion, we have learnt the difference between typeof
in javascript and typescript, and how keyof typeof
can be used to create a strict literal union of the keys of the object(or perhaps, enums) in consideration.
For more resources,