Union of keyof keys from a type in typescript

Union of keyof keys from a type in TypeScript

When working with TypeScript, you may come across a scenario where you need to create a union of the keys from a specific type. This can be useful in various situations, such as when you want to create a type-safe way of accessing properties or when you need to perform operations on a specific subset of keys. In this blog post, we will explore different solutions to achieve this in TypeScript.

Solution 1: Using keyof and typeof

The first solution involves using the keyof operator along with the typeof operator to create a union of keys from a specific type. Here’s an example:

type Person = {
  name: string;
  age: number;
  address: string;
};

type PersonKeys = keyof typeof Person;

// Output: "name" | "age" | "address"
console.log(PersonKeys);

In this example, we define a type called Person with three properties: name, age, and address. We then use keyof typeof to create a union type called PersonKeys that represents the keys of the Person type.

Solution 2: Using mapped types

Another solution involves using mapped types to create a union of keys from a specific type. Here’s an example:

type Person = {
  name: string;
  age: number;
  address: string;
};

type PersonKeys = {
  [K in keyof Person]: K;
}[keyof Person];

// Output: "name" | "age" | "address"
console.log(PersonKeys);

In this example, we define a type called Person with three properties: name, age, and address. We then use mapped types to create an intermediate type where each property is mapped to itself. Finally, we use [keyof Person] to obtain a union of the keys from the Person type.

Solution 3: Using utility types

If you are using TypeScript 2.8 or later, you can leverage utility types to create a union of keys from a specific type. Here’s an example:

type Person = {
  name: string;
  age: number;
  address: string;
};

type PersonKeys = keyof Person;

// Output: "name" | "age" | "address"
console.log(PersonKeys);

In this example, we define a type called Person with three properties: name, age, and address. We then use the keyof operator directly on the Person type to obtain a union of its keys.

These are three different solutions to create a union of keyof keys from a type in TypeScript. Depending on your specific use case and TypeScript version, you can choose the solution that best fits your needs. Happy coding!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *