如何基于对象中的值限制对象类型?

时间:2020-06-03 15:00:37

标签: javascript typescript

现在我正在使用此类型别名:

export type Country = {
  name: 'USA' | 'Russia' | 'Bulgaria' | 'Romania' | 'Austria' | 'Great Britain' | 'Italy',
  code: 'us' | 'ru' | 'bg' | 'ro' | 'au' | 'gb' | 'it'
};

但是它允许创建不正确的对象:

{ name: 'USA', code: 'ru'}

为此目的创建类型的最佳方法是什么?

2 个答案:

答案 0 :(得分:6)

您可以使用有区别的联合方法:

import seaborn as sns
sns.boxplot(x='label',y='age',data=df)

更多阅读enter image description here

您还可以使用参数映射,但是随后您必须在界面上指定参数:

type Country = {
    name: 'USA',
    code: 'us',
} | {
    name: 'Russia',
    code: 'ru',
} | {
    name: 'Bulgaria',
    code: 'bg',
} | {
    name: 'Romania',
    code: 'ro',
} | {
    name: 'Austria',
    code: 'au',
} | {
    name: 'Great Britain',
    code: 'gb',   
} | {
    name: 'Italy',
    code: 'it',   
};

// works
const myCountry: Country = {
    name: 'USA',
    code: 'us',
};

// does not
const myCountry2: Country = {
    name: 'USA',
    code: 'ru',
};

两个示例here

的工作打字机游乐场

答案 1 :(得分:1)

手动构造此类类型不好。提供单一类型的防卫法院代码(您已经掌握了),并将其与类型为CountryCode -> CountryName的导出功能一起使用。您可能需要其他一些定义命名策略的参数(本地化,短/全名等)。

相关问题