1

我有以下 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;

我怎样才能做到这一点?

4

2 回答 2

3

你可以这样做:

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

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

例如。

const ptUrls = termsAndCondition.pt
于 2020-01-10T13:05:37.903 回答
1
type TermAndConditions = Record<'en' | 'pt', string[]>

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

于 2020-01-14T13:09:36.843 回答