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
TypeScript TS2322: Type 'typeof Foo' is not assignable to type 'IFoo'
提问by azz
I'm trying to compose some classes using ES2015 module syntax with TypeScript. Each class implements an interface in a .d.ts
file.
我正在尝试使用 ES2015 模块语法和 TypeScript 组合一些类。每个类在.d.ts
文件中实现一个接口。
Here is a MWE of the problem.
这是问题的 MWE。
In a .d.ts
file 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 classFoo
to IFoo
. However the interface IFoo
is implemented by instancesof that class. You need to do :
当您说foo: IFoo = Foo;
您要将班级分配Foo
给IFoo
. 但是,该接口IFoo
是由该类的实例实现的。你需要做:
foo: IFoo = new Foo;