返回泛型时打字稿推理错误

Typescript inference error when returning generics

我很难理解这个问题。

Typescript Playground

为什么 Typescypt 只能推断某些 return 类型(查看 playground)?我做错了什么?

就我所见,只有在使用泛型时才会发生这种情况。

提前致谢!

不是忽略它们,只是CustomError<{}>足以覆盖字符串和数字。 string2 都可以分配给类型 {}.

// No errors with either of these
const test: {} = 'Test';
const test2: {} = 2;

所以打字稿可以说 return 类型是 CustomError<{}> | CustomError<null>,或者说是 CustomError<{}> | CustomError<string> | CustomError<number> | CustomError<null>,但由于两者之间没有区别,打字稿使用较短的那个。

Playground Link

如果您将对象的大小写更改为更复杂的对象,使得字符串和数字不再与其匹配,那么您将看到数字和字符串出现在 return 类型中:

if(this.randomOperation() == false){
  return new CustomError({ hello: 'world });
}

Playground link