I struggled with the title, but the code example is very straightforward:
// 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
Is it possible to get the TypeScript compiler to infer that we've added the necessary properties to narrow down the union type? Is there a different way of structuring my types to avoid this kind of problem?