【问题标题】:Typescript alias not matching function signature打字稿别名与函数签名不匹配
【发布时间】:2017-09-04 21:40:09
【问题描述】:

我有如下类型别名

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) =&gt; string 类型的参数不可分配给“Efg”类型的参数。参数“item”和“item”的类型不兼容。类型“T”不能分配给类型“T”。存在同名的两种不同类型,但它们不相关。

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

【问题讨论】:

  • T 是什么?你确定这两个定义是一样的吗?

标签: typescript


【解决方案1】:

为了使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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-17
    • 2018-03-24
    • 2023-04-04
    • 1970-01-01
    • 2020-07-28
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多