索引嵌套对象时返回类型不符合预期的TypeScript问题
TypeScript嵌套对象索引返回值类型不匹配问题
在通过泛型函数索引嵌套的colors对象时,TypeScript无法正确推断返回值的具体类型为string,导致返回值与声明的string类型不兼容,出现类型赋值错误。
原始代码
const colors = { sea: { aqua: "#fff", blue: "#fff", }, fruits: { red: "#fff", yellow: "#fff", }, }; type ColorsCategory = keyof typeof colors; const myFunction = <T extends ColorsCategory>( category: T, color: keyof (typeof colors)[T], ): string => { const chosenColor = colors[category][color]; return chosenColor; // ^? Type '{ sea: { aqua: string; blue: string; }; fruits: { red: string; yellow: string; }; }[T][string]' is not assignable to type 'string'. };
问题原因
TypeScript处理泛型T时,无法自动将(typeof colors)[T][keyof (typeof colors)[T]]的类型精确收窄到string。虽然我们明确所有属性值都是string,但TypeScript的类型系统需要更明确的约束才能确认这一点。
解决方案
以下三种方案都能解决这个问题:
方案1:显式断言返回值类型
直接将取值结果断言为string,明确告诉TypeScript该值的类型:const myFunction = <T extends ColorsCategory>( category: T, color: keyof (typeof colors)[T], ): string => { const chosenColor = colors[category][color]; return chosenColor as string; };方案2:定义统一的类型约束
先为颜色值定义一个统一类型,再约束colors对象的结构,让TypeScript自动推断返回值为string:type ColorValue = string; type ColorGroup = Record<string, ColorValue>; const colors: Record<string, ColorGroup> = { sea: { aqua: "#fff", blue: "#fff", }, fruits: { red: "#fff", yellow: "#fff", }, }; type ColorsCategory = keyof typeof colors; const myFunction = <T extends ColorsCategory>( category: T, color: keyof (typeof colors)[T], ): ColorValue => { return colors[category][color]; };方案3:使用类型查询对齐返回值类型
通过类型查询语法,让返回值类型与实际取值的类型完全对齐,无需额外断言:const myFunction = <T extends ColorsCategory>( category: T, color: keyof (typeof colors)[T], ): typeof colors[T][typeof color] => { return colors[category][color]; };
内容的提问来源于stack exchange,提问作者Stavros
相关产品推荐
相关产品推荐

