可以说我有以下代码
type Person = {
race: string
}
type Animal = {
species: string
}
export const adaptor = (
input: Person | Animal,
type: string
): string => {
switch (type) {
case 'person':
return printRace(input); <-- Type error
case 'animal':
return printSpecies(input); <-- Type error
}
};
function printRace(input: Person) {
return input.name
}
function printSpecies(input: Animal) {
return input.species
}
当前我得到错误:
Argument of type 'Person | Animal' is not assignable to parameter of type 'Person'.
Property 'name' is missing in type 'Animal' but required in type 'Person'.ts(2345)
在第一种情况下(另一种情况下类似的错误)。
我怎样才能printRace
知道输入永远不会是类型Animal
?
目前,我可以实现的唯一方法是强制转换:
return printRace(input as Person);
还有另一种方法吗?
我认为将type
直接包含在Person
andAnimal
类型中会更好。好处是您不需要default
在switch语句中包含a ,因为Typescript知道您已经提供了一个case的所有可能值input.type
type Person = {
type: 'person',
race: string
}
type Animal = {
type: 'animal',
species: string
}
export const adaptor = (
input: Person | Animal,
): string => {
switch (input.type) {
case 'person':
return printRace(input);
case 'animal':
return printSpecies(input);
}
};
function printRace(input: Person) {
return input.race
}
function printSpecies(input: Animal) {
return input.species
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句