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

如何让TypeScript的hasItem函数确保返回true时singleton.item已定义?

如何让hasItem函数返回true时确保singleton.item已定义?

先看这段TypeScript代码:

type MyItem = {
  nested: { id: string }
}

type State = {
  item?: MyItem
}

const hasItem = (state: State) => {
  return state.item !== undefined
}

const singleton: State = {
  item: undefined
}

function other() {
  singleton.item = { nested: { id: 'world' } }
}

function main() {
  other()

  if (!hasItem(singleton)) return;

  console.log(`hello ${singleton.item.nested.id}`) // 这里报类型错误:singleton.item可能为undefined
}

main()

问题核心是:TypeScript无法识别hasItem(singleton)返回true时,singleton.item已经处于已定义状态,导致后续访问属性时触发类型错误。

解决方法很直接——把hasItem改成类型谓词函数,明确告诉编译器函数返回true时参数的类型:

// 用Required工具类型将State的可选属性转为必选
const hasItem = (state: State): state is Required<State> => {
  return state.item !== undefined
}

也可以直接指定具体的收缩类型:

const hasItem = (state: State): state is { item: MyItem } => {
  return state.item !== undefined
}

修改完成后,当hasItem(singleton)返回true时,TypeScript会自动将singleton的类型收窄为item属性必存在的版本,后续访问singleton.item.nested.id就不会再触发类型错误了。

原理是:类型谓词(state is X)是TypeScript提供的语法,用于在函数返回true时,让编译器将参数类型收窄为指定的类型,以此实现分支判断中的类型安全。

内容的提问来源于stack exchange,提问作者Guilherme Oderdenge

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 22:55:27