Typescript别名不匹配函数签名

时间:2017-09-04 21:40:10

标签: typescript

我有类型别名,如下所示

export type Abc = string;
export type Efg = <T>(item: T): Abc

现在我在下面使用它:

export interface SomeInterface<T> {
  someField: (item?: T) => Abc;
}

我有一个接收Efg的方法。

someMethod(methodToCall: Efg);

现在,当我尝试像这样调用someMethod时,我收到错误

  

obj.someMethod(someInterfaceObject.someField);

     

TS2345:类型(item?: T) => string的参数不能分配给'Efg'类型的参数。参数'item'和'item'的类型不兼容。类型“T”不能分配给“T”类型。存在两种具有此名称的不同类型,但它们是不相关的。

请注意,这适用于typescript 1.8.9,但我正在升级到typescript 2.4.2。另请注意,我还尝试在item?: T类型中创建项目可选项(例如Efg),在SomeInterface.someField中强制使用项目,但它会给我同样的错误。

1 个答案:

答案 0 :(得分:0)

为了使obj.someField符合SomeInterface.someFieldobj.someField必须是通用的。以下是一个工作示例:

export type Abc = string;
export type Efg = <T>(item: T) => Abc;
export interface SomeInterface { someField: <T>(item: T) => Abc; }

declare class Foo {
  someMethod(methodToCall: Efg): any;
}
declare const obj: SomeInterface;
new Foo().someMethod(obj.someField); // works
相关问题