How to use Objects Types In Javascript
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.
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' }
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: