泛型
在TypeScript中,泛型是一种强大的工具,它允许我们编写可重用的组件,这些组件可以适应多种类型。
1. 泛型约束(Generic Constraints)
泛型可以被约束在一个特定的类型或类型接口上,确保传递给泛型的类型满足一定的条件。例如,如果我们希望一个函数只接收具有 length
属性的类型,我们可以这样做:
interface Lengthwise {
length: number;
}
function printLength<T extends Lengthwise>(item: T): void {
console.log(item.length);
}
const stringLength = "hello";
printLength(stringLength); // OK, strings have a length property
const objectWithoutLength = {
name: "World" };
printLength(objectWithoutLength); // Error, no length property
<T extends Lengthwise>
确保 T
必须具有 length
属性。
2. 类型推断(Type Inference with Generics)
TypeScript允许在某些情况下自动推断泛型的类型,特别是在函数调用时。例如,使用 infer
关键字可以从函数类型中提取返回值类型:
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function identity<T>(arg: T): T {
return arg;
}
type IdentityReturnType = ReturnType<typeof identity>; // IdentityReturnType is inferred as 'string'
在这里,ReturnType
会从函数类型中提取返回值类型。
3. 多参数泛型(Multi-Parameter Generics)
可以定义接受多个泛型参数的类型或函数:
interface Pair<T, U> {
first: T;
second: U;
}
function createPai