Create a Type from an object's Keys in TypeScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Create a Type from an object's Keys in TypeScript #

Use the keyof typeof syntax to create a type from an object's keys, e.g. type Keys = keyof typeof person. The keyof typeof syntax returns a type that represents all of the object's keys as strings.

index.ts
const person = { name: 'Tom', age: 30, country: 'Chile', }; // 👇️ type Keys = "name" | "age" | "country" type Keys = keyof typeof person; // 👇️ type Values = string | number type Values = typeof person[Keys];

We used keyof typeof to create a type from an object's keys.

If you need to get a type that represents the keys of another type, you would use keyof MyType.
index.ts
type Person = { name: string; age: number; country: string; }; // 👇️ type Keys = "name" | "age" | "country" type Keys = keyof Person;

Notice that we didn't use typeof, because Person is a type and not an object.

If you need to get a type of the object's values, use a const assertion when defining the object.

index.ts
const person = { name: 'Tom', age: 30, country: 'Chile', } as const; // 👈️ const assertion // 👇️ type Keys = "name" | "age" | "country" type Keys = keyof typeof person; // 👇️ type Values = "Tom" | 30 | "Chile" type Values = typeof person[Keys];

The as const syntax makes the properties of the object readonly, which means that the values cannot be changed.

index.ts
// 👇️ const person: { // readonly name: "Tom"; // readonly age: 30; // readonly country: "Chile"; // } const person = { name: 'Tom', age: 30, country: 'Chile', } as const; // 👈️ const assertion
This is useful because TypeScript is able to set the type of the values to the specific literals.

Had we not used a const assertion, we would get much more generic types like string and number.

index.ts
// 👇️ const person: { // name: string; // age: number; // country: string; // } const person = { name: 'Tom', age: 30, country: 'Chile', };

This is probably not what you want if you need a union type containing the object's values.

index.ts
const person = { name: 'Tom', age: 30, country: 'Chile', } as const; // 👇️ type Keys = "name" | "age" | "country" type Keys = keyof typeof person; // 👇️ type Values = "Tom" | 30 | "Chile" type Values = typeof person[Keys];

You can use the square brackets syntax to get the type of any of the object's values.

index.ts
const person = { name: 'Tom', age: 30, country: 'Chile', } as const; // 👇️ type V1 = "Tom" type V1 = typeof person['name']; // 👇️ type V2 = 30 type V2 = typeof person['age']; // 👇️ type V3 = "Chile" type V3 = typeof person['country'];
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.