Câu hỏi phỏng vấn Typescript
Câu hỏi

How do we create an enum with string values?

Câu trả lời

To create an enum with string values in TypeScript, you can follow several approaches, each suitable for different scenarios depending on your specific requirements. Here are the methods:

Using Enums

The most straightforward way to create an enum with string values is by directly assigning string literals to the enum members. This approach is simple and provides a clear structure for defining a set of named values, each associated with a specific string.

typescript Copy
enum Color {
  Red = "FF0000",
  Green = "00FF00",
  Blue = "0000FF",
}

In this example, an enum named Color is created with string values representing colors in hexadecimal format. You can then use this enum like so:

typescript Copy
const myColor: Color = Color.Red;
console.log(myColor); // Output: "FF0000"

This method is beneficial for creating a finite set of values that are known at compile time[8].

Using Union Types

Union types allow for more flexibility by combining multiple types with the | operator. They enable you to specify a variable to be one of several predefined string values without the rigid structure of an enum.

typescript Copy
type Color = "FF0000" | "00FF00" | "0000FF";

This approach is more open-ended and is useful when you want to allow any string value within a specified set without necessarily needing the additional structure that enums provide[8].

Using Object Mapping

Object mapping involves creating an object with string values and using the keyof operator along with typeof to define a type representing its keys. This method is useful when you want to map strings to more complex values or when you need to ensure the values are u...

junior

junior

Gợi ý câu hỏi phỏng vấn

junior

What is a TypeScript Map file?

junior

What is the difference between types String and string in TypeScript?

junior

What is Type Erasure in TypeScript?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào