为何TypeScript编译器会将已知返回值的函数推断为原始类型?
TypeScript类型推断的两种不同表现
先看这段代码:
const message = Math.random() > 0.5 ? "hello, can you hear me" : null;
TS编译器会将message的类型推断为*"hello, can you hear me" | null*,这完全符合逻辑,因为这个变量确实有两种明确的可能取值。
但再看下面这个函数定义:
const getName = () => "John Gump";
虽然函数的返回值是固定不变的John Gump,但TS却把getName的返回类型推断为*string原始类型,而非具体的字面量类型"John Gump"*。
内容的提问来源于stack exchange,提问作者Mehdi Raash
相关产品推荐
相关产品推荐

