使用数组对象中的某个属性的值创建类型?

时间:2019-04-18 11:37:08

标签: typescript

我在数组中有对象。所有对象都具有属性code

export const languageCodeToLanguageOption = [
    { code: 'cs', displayOrder: 1, text: 'Česky' },
    { code: 'zhhans', displayOrder: 2, text: '简体中文' },
];

如何创建具有所有code值的类型,而不必像下面所做的那样重复它们?

export type LanguageCode = 'cs' | 'zhhans';

1 个答案:

答案 0 :(得分:0)

我知道了

export const languageCodeToLanguageOption = [
    { value: 'cs', displayOrder: 1, text: 'Česky' },
    { value: 'zhhans', displayOrder: 2, text: '简体中文' },
] as const;

export type LanguageCode = typeof languageCodeToLanguageOption[number]['value'];