How to useObject Mapping in Typescript
Object mapping involves creating an object with string values and using keyof
to define a type representing its keys.
Example: In this example, using object mapping, we define objects Color
and Days
with string values. We then create types ColorKey
and DaysKey
representing the keys of these objects. We assign keys to variables myColor
and today
, logging their outputs, resulting in “Red” and “Wednesday” respectively.
const Color = {
Red: "FF0000",
Green: "00FF00",
Blue: "0000FF",
} as const;
const Days = {
Monday: "Mon",
Tuesday: "Tue",
Wednesday: "Wed",
Thursday: "Thu",
Friday: "Fri",
} as const;
type ColorKey = keyof typeof Color;
type DaysKey = keyof typeof Days;
const myColor: ColorKey = "Red";
const today: DaysKey = "Wednesday";
console.log(myColor); // Output: "Red"
console.log(today); // Output: "Wednesday"
Output:
Red
Wednesday
How to Create an Enum With String Values in TypeScript ?
To create an enum with string values in TypesScript, we have different approaches. In this article, we are going to learn how to create an enum with string values in TypesScript.
Below are the approaches used to create an enum with string values in TypesScript:
Table of Content
- Approach 1: Using Enums
- Approach 2: Using Union Types
- Approach 3: Using Object Mapping
- Approach 4: Using String Literal Types with Const Assertion
Contact Us