繁体   English   中英

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

[英]Typescript can infer recursive function, but not recursive type

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 的情况下推断递归函数类型?

在打字稿 4.3.2 上。

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

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

游乐场链接

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

使用类表达式时是否支持循环引用?

'Class' 在它自己的类型注解中被直接或间接引用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM