我很难理解这个标题,但代码示例非常简单:
// Setup
interface Dog {
name: string;
}
interface Dachshund extends Dog {
length: number;
}
function isDachshund (dog: Dog): dog is Dachshund {
return (dog as Dachshund).length !== undefined;
}
// Problem
// We have an object that could match two different interfaces
let unknownDog: Dog | Dachshund = { name: "Rufus" };
// If it's not this specific interface, add the missing property
if (!isDachshund(unknownDog)) {
(unknownDog as Dachshund).length = 5;
}
unknownDog // compiler still thinks Dog | Dachshund, but we know for certain it's a Dachshund at this point
有没有可能让TypeScript编译器推断我们已经添加了必要的属性来缩小联合类型的范围?有没有一种不同的方式来组织我的类型来避免这种问题?