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

如何避免使用字符串作为索引类型?如何使LayerPropType为string[]类型?

解决方案:用字符串值对应的类型作为索引

问题的核心是TypeScript的类型系统和值系统完全独立,你不能直接用值tagName去做类型索引,得用它对应的类型层面的表示。下面是两种可行的方法:

方法一:直接使用字符串字面量类型

直接把目标键名作为字符串字面量写在索引里,或者先定义类型层面的键名:

type WMSLayerProps = {
  Name?: string
  CRS?: string[]
}

// 方式1:直接用字面量索引
type LayerPropType = WMSLayerProps["CRS"]; // 类型为 string[] | undefined

// 方式2:先定义类型层面的键名
type TagName = "CRS";
type LayerPropType2 = WMSLayerProps[TagName]; // 同样是 string[] | undefined

// 如果需要确保类型是string[](去掉可选的undefined)
type LayerPropTypeRequired = NonNullable<WMSLayerProps["CRS"]>; // 类型为 string[]

方法二:通过typeof获取值的类型

因为你用const声明的tagName,TypeScript会自动推断它的类型是字面量类型"CRS"(而不是宽泛的string),所以可以用typeof tagName拿到这个字面量类型作为索引:

type WMSLayerProps = {
  Name?: string
  CRS?: string[]
}

const tagName = "CRS";
// 用typeof tagName获取值对应的字面量类型
type LayerPropType = WMSLayerProps[typeof tagName]; // 类型为 string[] | undefined

// 去掉undefined的版本
type LayerPropTypeRequired = NonNullable<WMSLayerProps[typeof tagName]>; // 类型为 string[]

如果你的tagName是用let声明的(默认类型会变成string),需要用as const强制让TypeScript保留字面量类型:

let tagName = "CRS" as const;
type LayerPropType = WMSLayerProps[typeof tagName]; // 正常得到string[] | undefined

内容的提问来源于stack exchange,提问作者pcace

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 12:55:09