javascript - typescript TS2322 : Type 'typeof Foo' is not assignable to type 'IFoo'

标签 javascript typescript ecmascript-6

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

这是问题的 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'.

这里有什么想法吗?

最佳答案

当您说 foo: IFoo = Foo; 时,您正在将 class Foo 分配给 IFoo。然而,IFoo 接口(interface)是由该类的实例 实现的。你需要做的:

foo: IFoo = new Foo;

关于javascript - typescript TS2322 : Type 'typeof Foo' is not assignable to type 'IFoo' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33536116/

相关文章:

给定索引后特殊字符的Javascript索引

javascript/jquery .animate() 色调旋转

javascript - 在 TypeScript 中使用 Promises 的异步函数的正确错误模式

typescript - 我做错了 Promise...我在这里错过了什么?

Javascript const 关键字的使用方式不同

缺少 JavaScript;在 for 循环初始化程序之后(来源未知

javascript - 使用javascript显示和隐藏sidenav

angular - 如何在 Angular 6 中构建具有多个组件的表单?

javascript - ES6 类中的作用域

javascript - 如何使用es6或lodash在javascript中按索引对两个数组进行分组?