我一直在努力将项目从TypeScript 2.3升级到2.4,但它证明相当令人沮丧和困惑。我收到了一些我无法理解的与泛型有关的错误。
我已经分解了一段代码并尽可能地简化了它:
interface Service {
serviceName: string;
}
interface TableParams {
selectionListLabelFn: <T>(item: T) => string;
}
const tableParams: TableParams = {
selectionListLabelFn: (service: Service) => service.serviceName
};
上面的代码会产生以下错误:
λ tsc test.ts
test.ts(9,7): error TS2322: Type '{ selectionListLabelFn: (service: Service) => string; }' is not assignable to type 'TableParams'.
Types of property 'selectionListLabelFn' are incompatible.
Type '(service: Service) => string' is not assignable to type '<T>(item: T) => string'.
Types of parameters 'service' and 'item' are incompatible.
Type 'T' is not assignable to type 'Service'.
为什么会这样?这对我没用。
答案 0 :(得分:0)
我不确定你想要达到的目标,但错误不是错误的。原因是selectionListLabelFn
被声明为通用委托,因此通用委托不应该传递给具有Service
参数的委托。您可以创建如下通用箭头函数:
const tableParams: TableParams = {
selectionListLabelFn: <T>(service: T) => ""
};
如果您希望selectionListLabelFn
与Service
绑定,可以尝试在界面上声明:
interface TableParams<T> {
selectionListLabelFn: (item: T) => string;
}
const tableParams: TableParams<Service> = {
selectionListLabelFn: (service: Service) => service.serviceName
};
版本之间的规则可能更严格,但我不一定会对错误感到惊讶。我想我可能与2.4
中包含的this项目有关