Typescript has the ability to automatically determine the type of a recursive function:
/**
* Typescript correctly infers the type as
*
* const referencesSelf: () => ...
*
* This indicates recursion within the function
*/
const referencesSelf = () => {
return referencesSelf;
};
However, it struggles to infer the type of a class with recursive properties:
class ReferencesSelf {
_self: () => ReferencesSelf;
constructor(gen: () => ReferencesSelf) {
this._self = gen;
}
}
/**
* Typescript gives a warning:
*
* `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;
});
I have two questions:
- Why does this happen? Is there any official documentation addressing this issue?
- Is there a workaround to make TS infer the recursive function type accurately without resorting to nil?
This information is based on Typescript version 4.3.2.