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

What does the pipe, | mean in TypeScript?

Câu trả lời

In TypeScript, the pipe symbol | is used to denote a union type, which is a way of declaring that a variable or parameter can hold a value of different types. The union type is essentially a way to say that a value can be one of several types, and it is represented by listing those types separated by the pipe symbol.

For example, if you have a variable that can hold either a number or a string, you would declare it as number | string. This tells TypeScript that the variable is allowed to hold a value of either type. Here's a practical example:

typescript Copy
let value: number | string;
value = 42; // OK
value = "hello"; // OK
value = false; // Error: Type 'boolean' is not assignable to type 'number | string'.

In this example, assigning a number or a string to value is perfectly fine, but trying to assign a boolean results in a type error because boolean is not pa...

junior

junior

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

expert

What are the differences between the private keyword and private fields in TypeScript?

expert

How the never datatype can be useful?

middle

What are some use cases of template literal types in TypeScript?

Bình luận

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

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