Typescript 似乎能够推断递归函数的类型:
/**
* Typescript correctly infers the type is
*
* const referencesSelf: () => ...
*
* Where the ellipsis means recursion of the function
*/
const referencesSelf = () => {
return referencesSelf;
};
但是,无法推断具有递归性质的类:
class ReferencesSelf {
_self: () => ReferencesSelf;
constructor(gen: () => ReferencesSelf) {
this._self = gen;
}
}
/**
* Typescript warns with:
*
* `foo' implicitly has type 'any' because it does not have a type annotation and is
* referenced directly or indirectly in its own initializer.ts(7022)
*/
const foo = new ReferencesSelf(() => {
return foo;
});
两个问题:
关于 Typescript 4.3.2。
答案 0 :(得分:0)
对于问题的第二部分,请使用 as
这样的关键字:
const foo = new ReferencesSelf(() => {return foo;}) as ReferencesSelf;
另见以下链接。 也许它可以帮助第一部分。
Are circular references supported when using class expressions?
'Class' is referenced directly or indirectly in its own type annotation