当“存在具有此名称的两种不同类型,但它们不相关”时,如何修复 Typescript 泛型类

问题描述 投票:0回答:1

考虑以下代码。 ColumnSorter 旨在通过字符串名称封装一组排序函数,然后将正确的排序函数应用于数组。

export class ColumnSorter<T> {
    constructor(private map: Map<string, (a: T, b: T) => number>) {
    }
    public sortBy<T>(sortcol: string, items: T[]): void {
        // *** DOES NOT COMPILE:
        items.sort(this.map.get(sortcol));
        // *** DOES NOT COMPILE EITHER:
        let fn: (a: T, b: T) => number = this.map.get(sortcol);
    }
}

// here is an example Quote arrays. Others could be position, account, etc.
// implementing with sort functions for that type.
const quoteFunctionMap: Map<string, (a: Quote, b: Quote) => number> = new Map([
    ['byLastPrice', (q1: Quote, q2: Quote) => {
        return q1.lastPrice - q2.lastPrice;
    }],
    ['bySymbol', (q1: Quote, q2: Quote) => {
        return q1.symbol.localeCompare(q2.symbol);
    }]
]);

let colsort = new ColumnSorter<Quote>(quoteFunctionMap);
let quotes: Quote[] = [new Quote(), new Quote()]; // blank quotes, for compile test
colsort.sortBy("byLastPrice", quotes);

问题是从地图中获取排序函数。错误消息很详细,但不足以让我找到问题的根源。我的代码中是否缺少某些内容?

Argument of type '((a: T, b: T) => number) | undefined' is not assignable to parameter of type '((a: T, b: T) => number) | undefined'.
  Type '(a: T, b: T) => number' is not assignable to type '(a: T, b: T) => number'. Two different types with this name exist, but they are unrelated.
    Types of parameters 'a' and 'a' are incompatible.
      Type 'T' is not assignable to type 'T'. Two different types with this name exist, but they are unrelated.
        'T' could be instantiated with an arbitrary type which could be unrelated to 'T'.ts(2345)
typescript generics
1个回答
3
投票

您的

ColumnSorter.sortBy
方法应使用类中的
T
泛型,而不是定义自己的。

export class ColumnSorter<T> {
  constructor(private map: Map<string, (a: T, b: T) => number>) {
  }
  // NOTE: changed from sortBy<T> to just sortBy below!
  public sortBy(sortcol: string, items: T[]): void {
    items.sort(this.map.get(sortcol));
    let fn = this.map.get(sortcol);
    if (!fn) {
      throw new Error(`No sorter exists for ${sortcol}`);
    }
    // ...
  }
} 
© www.soinside.com 2019 - 2024. All rights reserved.