Javascript TypeScript TS2322:类型“typeof Foo”不可分配给类型“IFoo”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33536116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:12:10  来源:igfitidea点击:

TypeScript TS2322: Type 'typeof Foo' is not assignable to type 'IFoo'

javascripttypescriptecmascript-6

提问by azz

I'm trying to compose some classes using ES2015 module syntax with TypeScript. Each class implements an interface in a .d.tsfile.

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

Here is a MWE of the problem.

这是问题的 MWE。

In a .d.tsfile I have:

在一个.d.ts文件中,我有:

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

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

My export is:

我的出口是:

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

And my import is:

我的进口是:

import Foo from "./foo";

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

The error here is:

这里的错误是:

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

Any ideas here?

这里有什么想法吗?

回答by basarat

When you say foo: IFoo = Foo;you are assigning the classFooto IFoo. However the interface IFoois implemented by instancesof that class. You need to do :

当您说foo: IFoo = Foo;您要将班级分配FooIFoo. 但是,该接口IFoo是由该类的实例实现的。你需要做:

foo: IFoo = new Foo;