Borislav Hadzhiev
Fri Mar 11 2022·2 min read
Photo by Maddie Collet
To create a type from an object's values:
keyof typeof
to get a type that represents the object's keys.const employee = { id: 1, name: 'James Doe', salary: 100, } as const; // 👈️ use const assertion // 👇️ type Keys = "id" | "name" | "salary" type Keys = keyof typeof employee; // 👇️ type Values = 1 | "James Doe" | 100 type Values = typeof employee[Keys];
The as const
syntax is called a
const assertion.
We used it to declare an immutable object.
We had to do this, because it helps us narrow down the type of the object's values.
// 👇️ const employee: { // readonly id: 1; // readonly name: "James Doe"; // readonly salary: 100; // } const employee = { id: 1, name: 'James Doe', salary: 100, } as const; // 👈️ use const assertion
The values of the object in the example above are typed as 1
, James Doe
and
100
, which is exactly what we need to get a type representing the object's
values.
readonly
and the values will never change.Had we not used a const assertion, we would get much more generic types for the object's values.
// 👇️ const employee: { // id: number; // name: string; // salary: number; // } const employee = { id: 1, name: 'James Doe', salary: 100, };
The example above does not use a type assertion, so the type of the object's
values would have been string | number
, which is probably not what you need.
We used keyof typeof to get the type of the object's keys.
const employee = { id: 1, name: 'James Doe', salary: 100, } as const; // 👇️ type Keys = "id" | "name" | "salary" type Keys = keyof typeof employee; // 👇️ type Values = 1 | "James Doe" | 100 type Values = typeof employee[Keys];
The keyof typeof
syntax returns a type that represents all of the object's
keys as strings.
To get a type of the object's values, we used square brackets and indexed the object using the type of the keys.
You can use this approach to get the type of a value that corresponds to a specific property as well.
const employee = { id: 1, name: 'James Doe', salary: 100, } as const; // 👇️ type Keys = "id" | "name" | "salary" type Keys = keyof typeof employee; // 👇️ type Values = 1 | "James Doe" | 100 type Values = typeof employee[Keys]; // 👇️ type V1 = 1 type V1 = typeof employee['id']; // 👇️ type V2 = "James Doe" type V2 = typeof employee['name']; // 👇️ type V3 = 100 type V3 = typeof employee['salary'];