How to use Mapped Types In Typescript
You can define your mapped type using the type alias in TypeScript that can be used to specify the keys of a particular type in an object.
Syntax:
type customType = {};
Example: The below code explains the use of the mapped types to declare specific type keys in an object.
type MyObject = {
[key: string]: number;
};
const obj: MyObject = {
a: 1,
b: 2,
c: 3
};
console.log(obj);
Output:
{ a: 1, b: 2, c: 3 }
How to Declare Specific Type of Keys in an Object in TypeScript ?
In TypeScript, object definitions can include specific key-value types using index signatures. You can declare specific types of keys in an object by using different methods as listed below:
Table of Content
- Using Mapped Types
- Using Interface
- Using Inline Mapped Types with type