Explain generics in TypeScript
Explain generics in TypeScript
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.
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.
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.
Here’s a simple example of a generic function:
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:
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
.
entry
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào