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

如何在TypeScript中将类型收窄为非可选字段类型?

无需类型断言:将可选字段转为必填的TypeScript类型处理方案

我有一个包含可选字段的TypeScript类型,希望返回一个结构相似但该字段为必填的类型。示例代码如下:

type Foo = {
  x?: string
}
type Bar = {x: string}

const fn = (foo: Foo): Bar => {
  if (foo.x) {
    return foo
  }

  throw new Error()
}

这段代码无法通过类型检查,因为foo并未被收窄为Bar类型。请问无需使用类型断言的情况下能否解决该问题?


解决方案1:自定义类型守卫函数

通过编写类型守卫函数,明确告知TypeScript满足条件时foo的类型为Bar,实现精准类型收窄:

type Foo = {
  x?: string
}
type Bar = {x: string}

// 类型守卫:判断传入值是否符合Bar类型
function isBar(foo: Foo): foo is Bar {
  return typeof foo.x === 'string';
}

const fn = (foo: Foo): Bar => {
  if (isBar(foo)) {
    // 此时foo已被收窄为Bar类型,可直接返回
    return foo
  }

  throw new Error()
}

解决方案2:解构后重新构造对象

解构出可选字段后重新构造返回对象,TypeScript会基于if (x)的判断自动推断返回对象符合Bar类型:

type Foo = {
  x?: string
}
type Bar = {x: string}

const fn = (foo: Foo): Bar => {
  const { x } = foo
  if (x) {
    // 重新构造对象,TypeScript识别x为必填string类型
    return { x }
  }

  throw new Error()
}

内容的提问来源于stack exchange,提问作者Steven Noble

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 10:55:24