You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从字符串数组提取类型?TypeScript类型定义报错求助

问题解决步骤

错误原因分析

你的代码存在三个核心问题:

  1. 数组默认被TypeScript推断为string[],无法获取具体的字符串字面量类型
  2. 类型定义中使用了错误的变量名(nationStates应为translationSettings)
  3. 错误使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 01:57:08