Open In App

How to Convert an Array of Keys into a Union Type of Objects ?

Last Updated : 26 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We can convert an array of keys into a union type of objects in typescript using mapped types or object types. The process involves dynamically creating types based on the provided array of keys, resulting in a union type that represents all possible combinations of objects with those keys.

Using Mapped Types

Mapped types allow us to transform each property in a type according to a given mapping. We can use the Record<K, V> mapped type to create a union type of object where the keys are taken from an array.

Syntax:

type NewType = Record<KeyType, ValueType>;

Example: To demonsrtate initializes an array of keys, then defines a union type “Person” using the Record<K, V> mapped type. It assigns an object with properties matching the keys to a variable “person” of type “Person”.

JavaScript
const keys = ['name', 'age', 'gender'] as const;

type Person = Record<typeof keys[number], string>;

// Example usage
let person: Person = {
    name: 'Alice',
    age: '30',
    gender: 'female'
};

console.log(person);

Output

{ name: 'Alice', age: '30', gender: 'female' }

Using Objects Types

In this method we can directly define an object type with properties derived from an array of keys

Syntax:

type NewType = {
    [K in keyof KeysArray]: ValueType;
};

Example: To demonsrtate an array “keys” holds keys, and a “Person” type is defined with properties derived from the array. Each property of “Person” is defined as [K in typeof keys[number]]: string, iterating over keys.

JavaScript
const keys = ['name', 'age', 'gender'] as const;
type Person = {
    [K in typeof keys[number]]: string;
};

// Example usage
let person: Person = {
    name: 'Bob',
    age: '25',
    gender: 'male'
};

console.log(person);

Output

{ name: 'Bob', age: '25', gender: 'male' }

Using Reduce Method

In this approach, we utilize the reduce method to convert an array of keys into a union type of objects.

Syntax:

type UnionFromKeys<T extends readonly string[]> = {
  [K in T[number]]: string;
};

Example:

JavaScript
type UnionFromKeys<T extends readonly string[]> = Record<T[number], string>;

const keys = ['name', 'age', 'gender'] as const;

type Person = UnionFromKeys<typeof keys>;

const person: Person = keys.reduce((acc, key) => {
  acc[key] = '';
  return acc;
}, {} as Person);

console.log(person);

Output:

{
  name: "",
  age: "",
  gender: ""
} 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads