I am trying to push value to an array but getting error from TypeScript.
Schema:
interface IUser extends Document {
contacts: Array<IContact>;
}
interface IContact {
status: 'pending' | 'requested' | 'contact';
userId: mongoose.Schema.Types.ObjectId;
}
const contactsSchema = new mongoose.Schema<IContact>({
status: {
type: String,
},
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users',
},
});
contacts: [contactsSchema],
And that's the code which I am getting error:
const requestedContact = {
status: 'requested',
userId: userId,
};
const pendingContact = {
status: 'pending',
userId: userAuth?._id,
};
userAuth?.contacts.push(requestedContact);
user?.contacts.push(pendingContact);
Error:
Argument of type '{ status: string; userId: mongoose.Schema.Types.ObjectId; }' is not assignable to parameter of type 'IContact'.
Types of property 'status' are incompatible.
Type 'string' is not assignable to type '"pending" | "requested" | "contact"'.ts(2345)
If I change union type to be only a string it will work but I really don't want to, can anyone explain what I am doing wrong here?