【问题标题】:How to assign a typed function to a generic function如何将类型化函数分配给泛型函数
【发布时间】: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);

Playground link

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    为您的比较函数参数定义一个类型:

    type CompareFn<T> = (a: T, b: T) => boolean;
    

    ...然后在构造函数的compare参数中使用:

    constructor(a : T, b: T, compare: CompareFn<T> = DefaultCompare) {
    // −−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^
    

    Playground link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-19
      • 2023-01-16
      • 1970-01-01
      • 2017-07-19
      • 1970-01-01
      • 2017-03-25
      • 2020-07-08
      • 2011-02-20
      相关资源
      最近更新 更多