How to use Template Literal Types In Javascript

Template literal types, introduced in TypeScript 4.1, provide a powerful way to manipulate string literal types. We can leverage template literal types to dynamically create union types of objects based on an array of keys.

Syntax:

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

Example:

JavaScript
type Keys = ['name', 'age', 'gender'];

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

type Person = UnionFromKeys<Keys>;

const person: Person = {
  name: "Alice",
  age: "30",
  gender: "female"
};

console.log(person);

Output:

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


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

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.

Table of Content

  • Using Mapped Types
  • Using Objects Types
  • Using Reduce Method
  • Using Template Literal Types:

Similar Reads

Using Mapped Types

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

Using Objects Types

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

Using Reduce Method

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

Using Template Literal Types:

Template literal types, introduced in TypeScript 4.1, provide a powerful way to manipulate string literal types. We can leverage template literal types to dynamically create union types of objects based on an array of keys....