我有以下定义:
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
答案 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
}