打字稿未在字符串并集类型数组中键入验证值

时间:2019-04-05 17:53:49

标签: typescript

我有以下定义:

type FruitType = 'Apple' | 'Orange' | 'Banana';
interface SurveyValues {
  favoriteFruit: FruitType;
  fruitAllergies: FruitType[];
}

// Everything correctly defined and no problems
const test1 = {
  favoriteFruit: 'Orange', // OK
  fruitAllergies: ['Apple','Banana'] // OK
} as SurveyValues;

const test2 = {
  favoriteFruit: 'Pizza', // Typescript correctly complains
  fruitAllergies: ['Apple','Banana'] // OK
} as SurveyValues;

const test3 = {
  favoriteFruit: 'Orange', // OK
  fruitAllergies: ['Pizza','Candy'] // ??? Typescript Doesn't complain ???
} as SurveyValues;

我不明白为什么Typescript将测试3的fruitAllergies值视为“有效”。这是一个限制吗?这是因为我使用语法将通用对象转换为SurveyValues吗?

我正在使用TypeScript 3.2.4

1 个答案:

答案 0 :(得分:0)

我看到后两个变量分配TypeScript Playground

出错

也就是说,我更喜欢输入变量而不是as对象。错误更简洁。

type FruitType = 'Apple' | 'Orange' | 'Banana';
interface SurveyValues {
  favoriteFruit: FruitType;
  fruitAllergies: FruitType[];
}

// Everything correctly defined and no problems
const test1: SurveyValues = {
  favoriteFruit: 'Orange', // OK
  fruitAllergies: ['Apple', 'Banana'] // OK
};

const test2: SurveyValues = {
  favoriteFruit: 'Pizza', // ERROR HERE
  fruitAllergies: ['Apple','Banana'] // OK
}

const test3: SurveyValues = {
  favoriteFruit: 'Orange', // OK
  fruitAllergies: ['Pizza','Candy'] // ERROR HERE
}

Second Playground