作为JavaScript开发人员,我是新手进行类型检查,我很难理解为什么这个简单的代码不起作用:
type Animal = {
id: number,
name: string,
type: 'dog' | 'cat'
};
type Dog = {
id: number,
name: string,
type: 'dog',
color: string
};
function printAnimal(animal: Animal): string {
return `${animal.type}: ${animal.name}`;
}
const buddy: Dog = {
id: 1,
name: 'Buddy',
type: 'dog',
color: 'black'
}
printAnimal(buddy);Run Code Online (Sandbox Code Playgroud)
我在这里想要实现的是拥有一个接受接口的方法.然而这给了我错误:Cannot call 'printAnimal' with 'buddy' bound to 'animal' because string literal 'dog' [1] is incompatible with string literal 'cat' [2] in property 'type'..
我尝试了什么:
interface Animal { …