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

TypeScript 4.4.3 如何让不匹配对象键的字符串触发类型错误

问题原因

你使用as SomethingParameterName[]类型断言的写法,相当于主动告知TypeScript编译器“该数组的类型一定符合SomethingParameterName[]”,编译器会跳过对数组元素的额外校验,自然不会触发'c'的类型错误。

解决方案

不要使用类型断言,直接给变量声明对应的类型即可:

const doSomething = ({ a, b }: { a: number, b: string }): boolean => {
  return a === 1 || b === 'secret'
}

type SomethingParameterName = keyof Parameters<typeof doSomething>[0]

// 直接给变量标注类型,不要加as断言
const orderedParameterNames: SomethingParameterName[] = [
  'b', 'c', 'a' // 此时'c'会直接触发类型错误
]

扩展说明

如果你需要保留数组的字面量常量特性(不希望类型被拓宽为普通数组),在TypeScript 4.4.3版本中可以结合readonly修饰符实现:

const orderedParameterNames: readonly SomethingParameterName[] = ['b', 'a'] as const
// 此时如果数组内出现'c'同样会触发类型错误,同时数组类型会保留为只读的字面量元组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:09:01