TypeScript – How to define model in combination with using mongoose populate?

You need to use a type guard to narrow the type from Types.ObjectId | User to User

If you are dealing with a User class, you can use this:

if (item.user instanceof User) {
    console.log(item.user.name);
} else {
    // Otherwise, it is a Types.ObjectId
}

If you have a structure that matches a User, but not an instance of a class (for example if User is an interface), you’ll need a custom type guard:

function isUser(obj: User | any) : obj is User {
    return (obj && obj.name && typeof obj.name === 'string');
}

Which you can use with:

if (isUser(item.user)) {
    console.log(item.user.name);
} else {
    // Otherwise, it is a Types.ObjectId
}

If you don’t want to check structures for this purpose, you could use a discriminated union.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)