打字稿可以推断递归函数,但不能推断递归类型

时间:2021-07-18 14:02:27

标签: typescript

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;
});

两个问题:

  1. 为什么?这种行为是否记录在某处?我找不到这方面的任何标注。
  2. 有没有办法让 TS 在不默认为 nil 的情况下推断递归函数类型?

关于 Typescript 4.3.2。

1 个答案:

答案 0 :(得分:0)

对于问题的第二部分,请使用 as 这样的关键字:

const foo = new ReferencesSelf(() => {return foo;}) as ReferencesSelf;

PlaygroundLink

另见以下链接。 也许它可以帮助第一部分。

Are circular references supported when using class expressions?

'Class' is referenced directly or indirectly in its own type annotation