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

Describe what are conditional types in TypeScript?

Câu trả lời

Conditional types in TypeScript are a powerful feature that allows developers to define types that depend on a condition. Essentially, they enable the type system to choose between types based on certain criteria, making the code more flexible and robust.

Definition and Syntax

A conditional type selects one of two possible types based on a condition expressed as a type relationship test. The syntax for a conditional type looks like this:

typescript Copy
T extends U ? X : Y

Here, T and U are types. The type T extends U ? X : Y means "if T is assignable to U, then use type X, otherwise use type Y."

How Conditional Types Work

Conditional types work similarly to ternary operations in JavaScript but operate at the type level. They are particularly useful when you want to create a type that can dynamically change based on the input types.

For example, consider a simple conditional type that checks whether a type is a string:

typescript Copy
type IsString<T> = T extends string ? "Yes" : "No";

In this example, IsString<T> will result in "Yes" if T is a string, otherwise "No".

Practical Applications

Conditional types are often used in advanced TypeScript patterns, such as type manipulation, higher-order functions, and API type definitions. They are crucial for creating generic utilities that can adapt their behavior based on the types passed to them.

  1. Type Manipulation: You can manipulate types based on conditions, extracting or modifying types dynamically. For instance, extracting property types from objects or picking certain types based on their structure.

  2. **API Type ...

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?

middle

What is Structural Typing?

entry

What is TypeScript and why would I use it in place of JavaScript?

Bình luận

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

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