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.
Cast the item.user
to User
, when the user is populated.
ItemModel.findById(id).populate("user").then((item: Item) => { console.log((<User>item.user).name);})