TypeScript TS7053类型错误求助:联合类型索引问题
解决TypeScript TS7053类型错误的方案
问题本质
你遇到的TS7053错误,核心原因是TypeScript无法通过联合类型的type字段自动推断出当前对象的具体属性。Test是FirstTest与SecondTest的联合类型,当你用data[type]访问属性时,TS无法确定当前data属于哪一个子类型,因此无法确认text或heading属性是否存在,只能将其推断为any类型并抛出错误。
可行解决方法
方法一:在switch分支内直接访问属性
最简洁的方式是移除提前提取content的步骤,在每个case分支中直接访问对应属性。TS会在switch的分支判断中自动收窄类型,确保类型安全:
const foo = (data: Test) => { switch (data.type) { case 'heading': return data.heading.value; case 'text': return data.text[0].value; } };
方法二:通过类型映射+泛型实现类型安全访问
如果需要复用属性提取逻辑,可以先定义类型映射关联type值与对应属性,再用泛型函数约束类型:
type TestValue = { value: string; }; type FirstTest = { type: 'text'; text: TestValue[]; }; type SecondTest = { type: 'heading'; heading: TestValue; }; type Test = FirstTest | SecondTest; // 定义type值与对应属性类型的映射 type TestTypeMap = { text: TestValue[]; heading: TestValue; }; // 泛型函数约束输入类型与type值匹配 const foo = <T extends keyof TestTypeMap>(data: Extract<Test, { type: T }>) => { const content = data[data.type] as TestTypeMap[T]; switch (data.type) { case 'heading': return content.value; case 'text': return content[0].value; } };
这里Extract<Test, { type: T }>确保传入的data与指定type严格匹配,TestTypeMap明确了每个type对应的属性类型,让TS能精准推断content的类型。
方法三:类型断言(临时应急,不推荐)
如果只是临时跳过类型检查,可以用类型断言强制指定类型,但这种方式会绕过TS的类型校验,存在潜在风险:
const foo = (data: Test) => { const { type } = data; const content = (data as any)[type]; switch (type) { case 'heading': return content.value; case 'text': return content[0].value; } };
注意:一旦类型定义发生变更,断言会导致类型错误无法被TS检测到,因此不推荐在生产代码中使用。
内容的提问来源于stack exchange,提问作者7ueun
相关产品推荐
相关产品推荐

