使用Object Literal替代Switch语句遇TypeScript类型错误求助
问题分析
你碰到的TS(7053)错误,核心原因是:fruit参数是string类型,但fruitCategory对象的键只有apple/orange/watermelon/default这几个固定值,TypeScript无法保证传入的string一定是对象的合法键,所以直接用fruit去索引对象会触发类型检查错误。另外还要注意,你的函数声明返回string[],但两种写法里的default分支都返回了字符串'Not found',这本身也不符合返回类型要求,得一起修正。
解决方案
下面给几种可行的修正方式:
方式一:给对象添加字符串索引签名
明确告诉TypeScript,这个对象允许用任意字符串作为键,同时修正default的返回值为数组以匹配函数返回类型:
const fruits = (fruit: string): string[] => { const fruitCategory: { [key: string]: string[] } = { apple: state.apple, orange: state.orange, watermelon: state.watermelon, default: ['Not found'], }; return fruitCategory[fruit] ?? fruitCategory.default; };
方式二:缩小参数的类型范围
把fruit的类型从string改成对象键的联合类型,让TS明确知道传入的只能是合法键:
type FruitType = 'apple' | 'orange' | 'watermelon' | string; const fruits = (fruit: FruitType): string[] => { const fruitCategory = { apple: state.apple, orange: state.orange, watermelon: state.watermelon, default: ['Not found'], }; return fruitCategory[fruit as keyof typeof fruitCategory] ?? fruitCategory.default; };
方式三:直接用类型断言处理索引
如果不想修改参数类型,也可以在索引时用类型断言跳过TS的检查:
const fruits = (fruit: string): string[] => { const fruitCategory = { apple: state.apple, orange: state.orange, watermelon: state.watermelon, default: ['Not found'], }; return fruitCategory[fruit as keyof typeof fruitCategory] ?? fruitCategory.default; };
额外提示
原来的switch写法里,default分支返回'Not found'是单个字符串,和函数声明的string[]返回类型冲突,所以不管用哪种写法,都要把default的返回值改成数组形式,否则还会触发另一个类型错误。
内容的提问来源于stack exchange,提问作者NewDev
相关产品推荐
相关产品推荐

