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

TypeScript中使用never类型限制对象属性报错的原因与解决办法

禁止对象出现指定属性的TypeScript错误解析

错误原因

你写的type T = { a: string, b: never }里,b是必填属性,TypeScript要求所有必填属性必须出现在对象中。但never类型没有任何合法取值——你既没法给b赋值(任何值都不符合never类型),又不能省略这个必填属性,所以直接触发了属性缺失的错误。

解决方法

要禁止对象出现指定属性,需要把目标属性设为可选且类型为never,这样既允许不写该属性,又会在你不小心写出该属性时报错。

写法1:直接定义类型

type T = { a: string } & { b?: never }

const t1: T = { a: '123' } // 正常通过
const t2: T = { a: '123', b: undefined } // 报错:类型undefined不能赋值给never
const t3: T = { a: '123', b: 'test' } // 报错:类型string不能赋值给never

写法2:封装通用工具类型

如果需要禁止多个属性,可以封装一个通用类型,方便复用:

// 工具类型:禁止对象包含指定属性
type ForbidProps<Base, Props extends string> = Base & {
  [P in Props]?: never
}

// 使用示例:禁止包含b、c属性
type T = ForbidProps<{ a: string }, 'b' | 'c'>

const t1: T = { a: '123' } // 正常通过
const t2: T = { a: '123', b: 'test' } // 报错
const t3: T = { a: '123', c: 123 } // 报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 08:27:23