在 TypeScript 的箭头函数中使用泛型
我们可以通过在函数参数之前设置它来在箭头函数中使用泛型,例如 const returnInArray = <T>(value: T): T[] => {}
。 然后可以在调用函数时传递泛型,例如 returnInArray<string>('hello')
。
const returnInArray = <T>(value: T): T[] => {
return [value];
};
const strArray = returnInArray<string>('hello');
const numArray = returnInArray<number>(100);
泛型允许我们将类型作为变量传递给函数和类。
泛型使用箭头括号在函数参数之前指定。
调用具有泛型的函数的语法是相同的——它在函数的参数之前传递。
请注意,我们不必在调用函数时显式提供泛型。 在这种情况下,TypeScript 将能够根据传入参数的类型推断泛型的类型。
const returnInArray = <T>(value: T): T[] => {
return [value];
};
// const strArray: string[]
const strArray = returnInArray('hello');
// const numArray: number[]
const numArray = returnInArray(100);
我们可以对泛型应用约束,只允许传递某些类型。
type CanRun = {
run(): void;
};
// 只能用具有 run() 方法的对象调用
const callRun = <T extends CanRun>(obj: T) => {
obj.run();
};
// the animal runs
callRun({ run: () => console.log('the animal runs') });
class Dog {
run() {
console.log('the dog runs');
}
}
callRun(new Dog()); // the dog runs
callRun 箭头函数只能使用具有属性 run 的对象调用,该属性是返回类型为 void 的函数。
如果我们尝试使用不满足 CanRun 类型的类型调用函数,我们会得到一个错误。
type CanRun = {
run(): void;
};
const callRun = <T extends CanRun>(obj: T) => {
obj.run();
};
// ⛔️ Argument of type 'number' is not assignable
// to parameter of type 'CanRun'.ts(2345)
callRun(100);
当我们需要保证只能使用包含某些属性的对象调用函数时,此模式非常常用。
所述对象可以是多种类型,但只要它包含指定的属性,它就可以用作函数的参数。
class Shark {
swim() {
console.log('The shark swims');
}
}
class Dolphin {
swim() {
console.log('The dolphin swims');
}
}
interface CanSwim {
swim(): void;
}
const callSwim = <T extends CanSwim>(obj: T): void => {
obj.swim();
};
callSwim<Dolphin>(new Dolphin());
callSwim<Shark>(new Shark());
callSwim 函数接受一个对象参数并调用它的 swim 方法。
该函数使用约束来确保它只获取包含函数类型 swim 属性的传递对象。
我们还可以在类的箭头函数中使用泛型。
class GenericArray {
public arr: (string | number)[] = [];
insert = <T extends string | number>(el: T): void => {
this.arr.push(el);
};
print = (): void => {
console.log(this.arr);
};
}
const ga1 = new GenericArray();
ga1.insert<string>('a');
ga1.insert<number>(1);
ga1.print(); // ?️ ['a', 1]
// ⛔️ Argument of type '{ hello: string; }' is not assignable
// to parameter of type 'string | number'.ts(2345)
ga1.insert({ hello: 'world' });
insert 类方法可以传递一个字符串或一个数字。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。