You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 09:15:59