I'm facing an issue when attempting to narrow down a type based on a property. To explain it better, here's a simplified version in code:
type User = {
id: number;
name: string;
}
type CreateUser = {
name?: string;
}
const user: User | CreateUser = { name: "Foo Bar" };
if (user.id) {
console.log(`Hello ${user.name}`)
}
My thought process is that user
could be either a User
or a CreateUser
, and we can differentiate based on the presence of the id
property. However, this approach fails with the error message:
Property 'id' does not exist on type 'CreateUser'
. Additionally, user.name
remains as string | undefined
instead of just being a string
. Is there a way to achieve this that I am missing?
Surprisingly, even this approach doesn't work:
if ("id" in user) {
console.log(`Hello ${user.name}`)
}
This results in
Property 'name' does not exist on type 'never'.
.