I've run into this typescript error
Property 'id' does not exist on type 'never'.
I've produced a simplified example here (code sandbox here)
interface Get {
id: number;
}
interface Delete {
id: number;
}
const isGet = (narrowMe: Get | Delete, narrowBy: string): narrowMe is Get =>
narrowBy === "GET";
const isDel = (narrowMe: Get | Delete, narrowBy: string): narrowMe is Delete =>
narrowBy === "DELETE";
const foo = (narrowMe: Get | Delete, narrowBy: string) => {
if (isGet(narrowMe, narrowBy)) {
return narrowMe.id;
}
if (isDel(narrowMe, narrowBy)) {
return narrowMe.id; // error happens here
}
};
The real code is more complex, but essentially, the problem I think is that the two interfaces above are identical. If I add a fake field to Get
interface, to make them different, then the error goes away. I'm struggling to find documentation on what exactly is happening here and how I can fix it or workaround it. Adding a fake field is hacky and I don't really want to combine Get
and Delete
into a shared type unless there is no other way.
Get
andDelete
interfaces are the same thing. TypeScript has something called duck typing, so after you check ifnarrowMe
comforms toGet
interface, TS knows it also comforms toDelete
interface as well, so your secondif
is never actually possible. Things like that are usually solved with a discriminant:I agree that it does look hacky, but that's just a nature of TypeScript type system. If two interfaces are the same, they describe the same set of possible objects. Their name just does not matter and you have to discriminate them somehow else.