从0开始的TypeScriptの十:泛型大揭秘
2023-12-12 08:46:24
泛型(Generics)是指在定义函数、接口或类的时候,不预先指定具体的类型,而在使用的时候再指定类型的一种特性。泛型可以让我们编写出更灵活、更可重用的代码。
在TypeScript中,泛型使用尖括号(<>)表示。例如,我们可以定义一个名为GenericFunction
的泛型函数,如下所示:
function GenericFunction<T>(x: T): T {
return x;
}
这个函数接受一个类型为T
的参数,并返回一个类型也为T
的值。我们可以通过以下方式使用这个函数:
const number = GenericFunction(10);
const string = GenericFunction("Hello, world!");
在第一行代码中,我们将数字10作为参数传递给GenericFunction
函数,函数返回数字10。在第二行代码中,我们将字符串"Hello, world!"
作为参数传递给GenericFunction
函数,函数返回字符串"Hello, world!"
。
泛型不仅可以用于函数,还可以用于接口和类。例如,我们可以定义一个名为GenericInterface
的泛型接口,如下所示:
interface GenericInterface<T> {
value: T;
}
这个接口定义了一个名为value
的属性,类型为T
。我们可以通过以下方式使用这个接口:
const numberObject: GenericInterface<number> = { value: 10 };
const stringObject: GenericInterface<string> = { value: "Hello, world!" };
在第一行代码中,我们创建了一个名为numberObject
的对象,它的类型是GenericInterface<number>
。我们将数字10作为value
属性的值。在第二行代码中,我们创建了一个名为stringObject
的对象,它的类型是GenericInterface<string>
。我们将字符串"Hello, world!"
作为value
属性的值。
泛型还可以用于类。例如,我们可以定义一个名为GenericClass
的泛型类,如下所示:
class GenericClass<T> {
value: T;
constructor(value: T) {
this.value = value;
}
getValue(): T {
return this.value;
}
}
这个类定义了一个名为value
的属性,类型为T
。我们还可以定义一个名为getValue
的方法,它返回value
属性的值。我们可以通过以下方式使用这个类:
const numberClass = new GenericClass(10);
const stringClass = new GenericClass("Hello, world!");
console.log(numberClass.getValue()); // 10
console.log(stringClass.getValue()); // "Hello, world!"
在第一行代码中,我们创建了一个名为numberClass
的对象,它的类型是GenericClass<number>
。我们将数字10作为value
属性的值。在第二行代码中,我们创建了一个名为stringClass
的对象,它的类型是GenericClass<string>
。我们将字符串"Hello, world!"
作为value
属性的值。在第三行代码中,我们调用numberClass
对象的getValue
方法,并打印其返回值。在第四行代码中,我们调用stringClass
对象的getValue
方法,并打印其返回值。
泛型是一个非常强大的特性,它可以让我们编写出更灵活、更可重用的代码。在TypeScript中,泛型可以用于函数、接口和类。