TypeScript数组中使用区分联合类型报错问题咨询
TypeScript联合类型数组的类型不匹配问题解决
问题背景
定义Circle、Square接口及Shape联合类型后,编写返回Shape[]的函数时,对象中的kind字段被TypeScript推断为string类型,而非预期的字面量类型(如"circle"、"square"),导致数组无法赋值给Shape[]类型,出现类型错误。
错误提示核心:
Type '{ kind: string; radius: number; sideLength?: undefined; }' is not assignable to type 'Shape'.
Types of property 'kind' are incompatible.
Type 'string' is not assignable to type "square".
原因分析
TypeScript默认会将对象字面量中的字符串值推断为宽泛的string类型,而非具体的字面量类型。这就导致数组元素的kind类型,与Shape联合类型中定义的字面量类型不兼容。
解决方案
1. 给数组变量显式指定Shape[]类型
直接告诉TypeScript数组的类型为Shape[],强制它按照联合类型的要求推断元素:
interface Circle { kind: "circle"; radius: number; } interface Square { kind: "square"; sideLength: number; } type Shape = Circle | Square; const getShapes = (): Shape[] => { const data: Shape[] = [ { kind: "circle", radius: 1 }, { kind: "square", sideLength: 3} ] return data; }
2. 使用as const断言字面量类型
通过as const让TypeScript将字符串值推断为具体的字面量类型,而非宽泛的string:
const getShapes = (): Shape[] => { const data = [ { kind: "circle" as const, radius: 1 }, { kind: "square" as const, sideLength: 3} ] return data; }
也可以对整个数组使用as const,但此时数组为只读类型,需要展开转成普通数组后返回:
const getShapes = (): Shape[] => { const data = [ { kind: "circle", radius: 1 }, { kind: "square", sideLength: 3} ] as const; return [...data]; }
3. 直接返回数组,不使用中间变量
当直接返回数组时,TypeScript会根据函数的返回类型Shape[]反向推断数组元素的类型,自动匹配联合类型:
const getShapes = (): Shape[] => { return [ { kind: "circle", radius: 1 }, { kind: "square", sideLength: 3} ]; }
内容的提问来源于stack exchange,提问作者Scribblemacher
相关产品推荐
相关产品推荐

