如何从字符串数组提取类型?TypeScript类型定义报错求助
问题解决步骤
错误原因分析
你的代码存在三个核心问题:
- 数组默认被TypeScript推断为
string[],无法获取具体的字符串字面量类型 - 类型定义中使用了错误的变量名(
nationStates应为translationSettings) - 错误使用
Partial工具类型——它用于将对象属性设为可选,完全不适用于字符串字面量类型场景
修正后的代码实现
1. 调整数组定义,启用字面量类型推断
给数组添加as const断言,让TypeScript将其推断为只读字面量元组,而非宽泛的string[]:
export const translationSettings = [ 'districtName', 'district', 'id', "area", "changeDate", "parcelId", 'typeBotanical', 'typeGerman', 'height', 'borough', 'owner', 'genus', 'genusGerman', 'diameterCrown', 'plantingYear', 'diameterTrunk', 'age', 'street', ] as const;
2. 正确定义元素类型
直接取数组元素的联合类型,无需多余工具类型:
export type TranslationSettings = typeof translationSettings[number];
此时TranslationSettings等价于所有数组元素的字符串字面量联合类型:"districtName" | "district" | "id" | ...
3. 正确使用类型约束
现在可以正常定义符合要求的对象:
const translation: Record<string, TranslationSettings> = { namgmk: 'districtName', gmk: 'district', uuid: 'id', afl: "area", statusdat: "changeDate", fsko: "parcelId" };
内容的提问来源于stack exchange,提问作者pcace
相关产品推荐
相关产品推荐

