我有一个函数,它返回这样一个类:
function createClass() {
return class implements ISomeInterface {/* ... */}
}
export { createClass }
但现在ESLint发出以下警告:
Missing return type on function.
并链接到此ESLint规则。
如何定义createClass
的返回类型以使ESLint满意?
给定以下与匿名类的实例类型相对应的接口,
interface ISomeInterface {
prop: string;
method(): void;
}
定义与类的构造函数相对应的接口也很有帮助。这将包括构造函数的任何静态属性,以及类的构造签名,如下所示:
interface SomeInterfaceConstructor {
new(prop: string): ISomeInterface;
}
new(prop: string): ISomeInterface
意味着如果您有一个类型为SomeInterfaceConstructor
的值c
,那么您可以调用new c("foobar");
并得到一个ISomeInterface
。(请注意,并不意味着SomeInterfaceConstructor
有一个名为"new"
的方法,尽管语法看起来是这样的(。
有了构造函数接口的名称,您可以简单地让createClass()
返回类型:
function createClass(): SomeInterfaceConstructor {
return class implements ISomeInterface {
constructor(public prop: string) { }
method() {
console.log("My prop is " + this.prop);
}
}
}
你可以看到它是有效的:
const c = createClass();
// const c: SomeInterfaceConstructor;
const i = new c("foobar");
// const i: ISomeInterface
i.method(); // My prop is foobar
export { createClass }
导出createClass()
时,可能需要导出SomeInterfaceConstructor
类型,如果ISomeInterface
尚未导出(或在其他地方定义(,则也需要导出。
到代码的游乐场链接