如何在TypeScript中将数组用作接口的字符串封闭可选值列表?
解决方法
你需要使用typeof names[number]来获取数组元素的联合类型,而非(typeof names)[string]。原因是as const声明的数组属于只读元组类型,它的索引类型是数字(0、1、2这类具体数字)而非通用字符串,所以用[string]会触发类型错误。
正确实现代码如下:
const names = [`x`, `y`, `z`] as const; interface MyInterface { name: typeof names[number]; // 自动推导为 "x"|"y"|"z" 的联合类型 } const myTest: MyInterface = { name: `x` // 正常通过类型校验 }; // 错误示例:传入不在数组中的值会触发TS报错 // const myBadTest: MyInterface = { name: `a` }; // 类型“"a"”不能赋值给类型“"x" | "y" | "z"”
如果需要复用这个联合类型,可以先定义类型别名:
const names = [`x`, `y`, `z`] as const; type NameType = typeof names[number]; interface MyInterface { name: NameType; }
这种写法的优势在于,当你修改names数组的元素时,联合类型和接口的约束会自动同步,不需要手动维护字符串字面量列表,同时能严格保证类型安全。
内容的提问来源于stack exchange,提问作者JDD
相关产品推荐
相关产品推荐

