What does the pipe, | mean in TypeScript?
What does the pipe, | mean in TypeScript?
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:
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
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào