为对象中作为键的字符串定义类型

问题描述 投票:0回答:1

我的国家/地区配置如下所示:

type CountryConfig = {
   [country: string]: {
      countryCode: string,
      callingCode: string,
      ...
   }
}

const balkanCountries: CountryConfig = {
   Albania: { countryCode: "AL", callingCode: "+355", ... },
   Bulgaria: { countryCode: "BG", callingCode: "+359", ... },
   Croatia: { countryCode: "HR", callingCode: "+385", ... },
   ...
}

我想用

balkanCountries
的键创建一个类型:

type BalkanCountry = keyof typeof balkanCountries

预期类型:

BalkanCountry = "Albania" | "Bulgaria" | "Croatia" | ...
,实际类型:
BalkanCountry = string | number

基于这个堆栈溢出线程中的答案这是预期的行为,我可以通过显式提取字符串来绕过数字类型:

type BalkanCountry = Extract<keyof typeof balkanCountries, string>

但是,我得到的输出类型仍然是

type BalkanCountries = string
,而不是文字的联合。

这意味着我可以做作业:

const currentCountry: BalkanCountry = "Spain" // typescript will not throw error

为什么会发生这种情况?如何确保

currentCountry
只能是
balkanCountries
中的键值?

注意:我使用的是 TypeScript ~5.0.4。

typescript
1个回答
0
投票

您必须删除类型定义才能从对象推断键。

const balkanCountries = {
   Albania: { countryCode: "AL", callingCode: "+355" },
   Bulgaria: { countryCode: "BG", callingCode: "+359",  },
   Croatia: { countryCode: "HR", callingCode: "+385",  },
} satisifies CountryConfig;

type BalkanCountry = keyof typeof balkanCountries
// "Albania" | "Bulgaria" | "Croatia"

TS游乐场

© www.soinside.com 2019 - 2024. All rights reserved.