TypeScript中如何对联合类型变量使用索引访问,解决TS7053报错
报错原因
TS 不允许用不确定所有联合子类型都包含的键去索引联合类型,你的 StateOne 和 StateTwo 没有公共属性,而 Index 包含的键分别属于两个不同的接口,所以直接访问会触发 TS7053 错误。
解决方案(按推荐度排序)
方案1:重构参数类型为可区分联合(最推荐,类型100%安全)
从根源上限制 state 和 index 必须匹配,不允许出现「StateOne配StateTwo的键」这种非法传参,TS可以自动推导索引合法,不需要任何断言:
type Index = 'name' | 'length' | 'width' | 'depth' | 'height' interface StateOne { name: string length: number } interface StateTwo { width: number depth: number height: number } // 把参数类型改写为两种合法组合的联合 type SwitchProps = | { state: StateOne, index: keyof StateOne } | { state: StateTwo, index: keyof StateTwo } function testFunction({state, index}: SwitchProps) { // 直接访问不会报错,TS能自动识别索引合法 const test = state[index] }
如果传参不匹配,TS会在调用阶段就直接报错,完全避免运行时风险。
方案2:添加类型守卫收窄类型
如果不能修改原有 SwitchProps 的定义,可以用类型守卫明确区分当前的状态类型,再做访问:
interface SwitchProps { state: StateOne | StateTwo index: Index } function testFunction({state, index}: SwitchProps) { let test: string | number // 判断当前index是否是StateOne的合法键 if (['name', 'length'].includes(index)) { test = (state as StateOne)[index as keyof StateOne] } else { test = (state as StateTwo)[index as keyof StateTwo] } }
方案3:简化断言写法(适合确定传参100%匹配的场景)
你现在的as unknown绕转写法可以简化,更清晰易读:
const test = state[index as keyof (StateOne | StateTwo)]
比你当前的写法少了不必要的类型转换,类型可读性更好。
内容的提问来源于stack exchange,提问作者jackdaw
相关产品推荐
相关产品推荐

