Apologies if this is obvious as I don't have much experience with sequelize yet. I am trying to get a field that is in the junction table CustomerContact. Currently I am getting a contact and then retrieving its attached customers
const contactList: Contact[] = await db()
.Contact.newActiveScope()
.withCustomers()
.findAll();
const mainCustomer: Customer = contactList[i].getMainCustomer();
const mainCustomerContacts = mainCustomer && mainCustomer?.customerContacts;
const thisCustomerContactRole = mainCustomerContacts?.find((c) => c.contactId === contact.id)?.role;
Outputting the mainCustomer gets me the following information
{
id: 'a94fd13a-1fdd-11ec-a12c-121c563gb2f5',
accountName: 'Test Tests',
CustomerContact: { role: 1, relationship: 2, status: 'active' }
}
I want to use the properties in CustomerContact, but trying to access it gives me a typescript error, saying CustomerContact does not exist on type ContactWithCustomerContactStatic, which has the following shape.
export type ContactWithCustomerContactStatic = Partial<Customer> &
Pick<CustomerContact, 'role' | 'relationship'>;
I associate the Customer in the Contact Model
this.belongsToMany(Customer, {
as: 'customers',
foreignKey: 'contactId',
otherKey: 'customerId',
through: CustomerContact as CustomerContactStatic,
});
this.addScope('withCustomers', {
include: [
{
as: 'customers',
model: Customer as CustomerStatic,
where: { isArchived: false },
required: false,
},
],
});
and vice versa
Customer.belongsToMany(Contact, {
as: 'contacts',
through: CustomerContact,
foreignKey: 'customerId',
otherKey: 'contactId',
});
Customer.addScope('contacts', () => ({
include: [
{
as: 'contacts',
attributes: ['id', 'firstName', 'lastName'],
model: (Contact as ContactStatic).newScope(),
required: false,
through: {
where: { status: CustomerContactStatus.active },
},
},
],
}));
I can technically retrieve the values, but the typescript error gives me pause.
I'm positive I'm missing something but having trouble determining what that something is. Any help would be appreciated!
CodePudding user response:
I believe Typescript is showing this error because of the way you are declaring the ContactWithCustomerContactStatic type.
export type ContactWithCustomerContactStatic = Partial<Customer> &
Pick<CustomerContact, 'role' | 'relationship'>;
When declaring this way you say to Typescript that ContactWithCustomerContactStatic type has the following shape
interface ContactWithCustomerContactStatic {
// all properties from Customer interface comes here
role // it's in the root
relationship // it's also in the root
}
But, they are not in the root of the object, given the output that you presented
{
id: 'a94fd13a-1fdd-11ec-a12c-121c563gb2f5',
accountName: 'Test Tests',
CustomerContact: { role: 1, relationship: 2, status: 'active' }
}
This should work
type ContactWithCustomerContactStatic = Partial<Customer>
& { customerContact: Pick<CustomerContact, 'role' | 'relationship'>
}
