如果根 属性 有一个变量名,如何在一行中键入一个 javascript 对象

How to type in one line an javascript object in Typescript, were a root property has a variable name

我有以下 javascript 对象:

var termsAndConditions = {
    pt: ["url1", "url2"],
    en: ["url3", "url4"]
}

而且我想用 Typescript 在一行中输入它。像这样:

const termsAndConditions: {[countryKey: Array<string>]} = {
    pt: ["url1", "url2"],
    en: ["url3", "url4"]
}

然后像这样使用它:

const ptUrls: Array<string> = termsAndConditions.pt;
const enUrls: Array<string> = termsAndConditions.en;

我怎样才能做到这一点?

你可以这样做:

const termsAndConditions: { [countryKey: string]: string[] } = {
    pt: ["url1", "url2"],
    en: ["url3", "url4"]
}

稍后您不需要添加额外的输入,因为它已经指定

例如

const ptUrls = termsAndCondition.pt
type TermAndConditions = Record<'en' | 'pt', string[]>

如果类型具有相同的值形状,您可以使用Record,使用联合类型作为 Record 的键将适合您的情况