javascript 定义对象的键

qij5mzcb  于 2023-05-15  发布在  Java
关注(0)|答案(3)|浏览(97)

我有以下目标:

type Currencies = "tl" | "us-dollar" | "euro"
const currenciesMap = {}

我想说的是,这个对象的键必须是Currencies类型中定义的值之一。
因此,对象看起来如下所示:

const currenciesMap = {
  tl: "₺",
  "us-dollar": "$",
  euro: "€"
}

所以typescript应该只允许定义这些键。
如何制作这种类型?
我以为这会奏效,但它没有:

const currenciesMap: { [key: Currencies[string]]: string } = {}

Typescript显示以下错误:

An index signature parameter type must be 'string', 'number', 'symbol', or a template literal type.
zujrkrfu

zujrkrfu1#

您可能正在寻找Typescript Record实用程序类型。这里有记录
Record等于

type Record<K extends string | number | symbol, T> = { [P in K]: T }
type Currencies = "tl" | "us-dollar" | "euro"
const currenciesMap: Record<Currencies, string> = {
  tl: "₺",
  "us-dollar": "$",
  euro: "€"
}

请注意,当以这种方式将变量声明为记录时,您将被迫声明所有可能的属性。如果您不想拥有所有这些,可以将其 Package 为Partial

type Currencies = "tl" | "us-dollar" | "euro"
const currenciesMap: Partial<Record<Currencies, string>> = {
  tl: "₺",
  "us-dollar": "$",
}
blpfk2vs

blpfk2vs2#

您不需要使用[string]访问Currencies。你应该说K in Currencies,如下所示:

type Currencies = 'tl' | 'us-dollar' | 'euro';

const currenciesMap: { [K in Currencies]: string } = {
  tl: '₺',
  'us-dollar': '$',
  euro: '€',
};
hwamh0ep

hwamh0ep3#

const currencies = {
  tl: "₺",
  "us-dollar": "$",
  euro: "€"
} as const

type Currency = typeof currencies[keyof typeof currencies]

用法

const log = (currency: Currency) => console.log(currency);
log(currencies.euro)

或者:

log("€")

相关问题