-1

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Does this answer your question? [Argument of type {stringVariable} not assignable to object of type {string literal}](https://stackoverflow.com/questions/71485918/argument-of-type-stringvariable-not-assignable-to-object-of-type-string-liter) – jonrsharpe Aug 22 '22 at 10:30
  • Hi, thank you! no still the same sadly – עמית שוקרון Aug 22 '22 at 10:31
  • _What_ is still the same? You certainly **don't** get the error that `'string' is not assignable to type '"pending" | "requested" | "contact"'` in contexts where the narrower type can be inferred or explicitly defined, and the linked post gives you two ways to do that (and has links to others). If you've tried applying them unsuccessfully, [edit] to give a [mre] that explains specifically what happened. – jonrsharpe Aug 22 '22 at 10:33
  • I took another look and this link indeed fixed my error. Thank you very much I will answer the question for people who might be getting this error too :) – עמית שוקרון Aug 22 '22 at 10:40
  • The point of the duplicate system is it _already does that_, if you accept it they get sent right to the existing answers. – jonrsharpe Aug 22 '22 at 11:34

1 Answers1

0

This fixed my error :

instead of this:

const requestedContact = {
    status: 'requested',
    userId: userId,
  };

  const pendingContact = {
    status: 'pending',
    userId: userAuth?._id,
  };

  userAuth?.contacts.push(requestedContact);
  user?.contacts.push(pendingContact);

I did it like this:

userAuth?.contacts.push({ status: 'requested', userId: userId });

user?.contacts.push({ status: 'pending', userId: userAuth?._id });