【发布时间】:2021-07-02 06:27:21
【问题描述】:
我不确定我是否正确地提出了这个问题,基本上我只是想强制比较函数采用 2 个参数,并且我希望它们都是相同的类型 (T),并且函数应该返回一个布尔值。
如何实现这样的。 我无法让它工作,下面的实现给出了以下错误:
“(a: CustomType, b: CustomType) => boolean”类型的参数不能分配给“(a: T, b: T) => boolean”类型的参数。 参数“a”和“a”的类型不兼容。 类型“T”不能分配给类型“CustomType”
function DefaultCompare<T>(a: T, b: T): boolean {
return a > b;
}
class ClassA<T> {
public a :T;
public b :T;
private compare : (a :T , b :T) => boolean;
constructor(a : T, b: T,compare= DefaultCompare) {
this.a = a;
this.b = b;
this.compare = compare;
}
}
interface CustomType {
cost : number,
name : string,
}
function CustomCompare (a: CustomType, b: CustomType): boolean {
return a.cost > b.cost;
}
const objA_1 = new ClassA<Number>(1, 2);
const _a : CustomType = { cost : 1, name : 'js'},
_b : CustomType = {cost : 2, name : 'ts'};
const objA_2 = new ClassA<CustomType>(_a, _b, CustomCompare);
【问题讨论】:
标签: typescript typescript-generics