【问题标题】:TypeScript TS2322: Type 'typeof Foo' is not assignable to type 'IFoo'TypeScript TS2322:类型“typeof Foo”不可分配给类型“IFoo”
【发布时间】:2015-11-05 03:22:54
【问题描述】:

我正在尝试使用 ES2015 模块语法和 TypeScript 编写一些类。每个类在.d.ts 文件中实现一个接口。

这是问题的 MWE。

.d.ts 文件中,我有:

interface IBar {
  foo: IFoo;
  // ...
}

interface IFoo {
  someFunction(): void;
  // ...
}

我的出口是:

// file: foo.ts
export default class Foo implements IFoo {
  someFunction(): void {} 
  // ... 
}
// no errors yet.

我的导入是:

import Foo from "./foo";

export class Bar implements IBar {
   foo: IFoo = Foo;
}

这里的错误是:

error TS2322: Type 'typeof Foo' is not assignable to type 'IFoo'.
Property 'someFunction' is missing in type 'typeof Foo'.

这里有什么想法吗?

【问题讨论】:

    标签: javascript typescript ecmascript-6


    【解决方案1】:

    当您说foo: IFoo = Foo; 时,您将 Foo 分配给IFoo。但是接口IFoo 是由该类的instances 实现的。你需要做的:

    foo: IFoo = new Foo;
    

    【讨论】:

    • 新手错误,以为我在 TypeScript 上做错了,实际上是 JS 的问题...谢谢。
    • 如果我想说变量不是实例化的类,而是一个实现接口但稍后实例化的类怎么办?这可能吗?
    猜你喜欢
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2017-04-10
    相关资源
    最近更新 更多