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

Explain generics in TypeScript

Câu trả lời

Generics in TypeScript are a powerful feature that allows developers to create flexible, reusable components by providing a way to use types as variables in their code. This feature is particularly useful in maintaining type safety across operations that work on different types of data.

What are Generics?

Generics introduce the concept of type variables to TypeScript, which can be used to capture the type passed into the component at the time of usage, rather than at the time of component definition. This means you can write a function, interface, or class that can handle a variety of types instead of being restricted to a single one.

How do Generics Work?

When defining a function, interface, or class, you can specify one or more placeholders for types using angle brackets (< >). These placeholders can then be used throughout the component to denote types that will only be specified when the component is used.

Example of a Generic Function

Here’s a simple example of a generic function:

typescript Copy
function identity<T>(arg: T): T {
    return arg;
}

In this function, T is a type variable that will represent whatever type is passed to the function when it is called. You can call this function with any type:

typescript Copy
let output1 = identity<string>("myString");
let output2 = identity<number>(100);

In the first call, T is replaced by string, and in the second, T is replaced by number.

Benefits of Using Generics

  1. Type Safety: Generics help in maintaining type safety. The TypeScript compiler can catch type mismatches at compile time, reducing runtime errors.
  2. Reusability: You can write a component once and reuse it with different types, reducing code duplication.
  3. Flexibility: Generics increase the flexibility of your code. You can write more generic and abstract algorithms that work on any type that complies with the constraints you ...
entry

entry

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

junior

How do we create an enum with string values?

middle

How to make a readonly tuple type in TypeScript?

junior

What does the pipe, | mean in TypeScript?

Bình luận

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

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