I have:
import sendgridClient from '@sendgrid/client'
sendgridClient.setApiKey(process.env.SENDGRID_API_KEY);
const sendgridRequest = {
method: 'PUT',
url: '/v3/marketing/contacts',
body: {
list_ids: [myId],
contacts: [
{
email: req.body.email,
custom_fields: {
[myFieldId]: 'in_free_trial'
}
}
]
}
};
await sendgridClient.request(sendgridRequest);
But my TypeScript language server gives me an error about sendgridRequest
:
Argument of type '{ method: string; url: string; body: { list_ids: string[]; contacts: { email: any; custom_fields: { e5_T: string; }; }[]; }; }' is not assignable to parameter of type 'ClientRequest'.
Types of property 'method' are incompatible.
Type 'string' is not assignable to type 'HttpMethod'.
Is there some way to resolve this?
method: 'PUT'
in your object is being inferred as string
, but it's expecting specific strings like "PUT" | "GET" | "POST"
. This because it has no specific type to try to match, and by default specific strings are just inferred as string
.
You can probably fix this by passing your object directly to the function. This casts the object as the right type because it's checked against what that function accepts:
await sendgridClient.request({
method: 'PUT',
url: '/v3/marketing/contacts',
body: {
list_ids: [myId],
contacts: [
{
email: req.body.email,
custom_fields: {
[myFieldId]: 'in_free_trial'
}
}
]
}
})
Or you can give your intermediate variable the correct type imported from the sendgrid module.
import sendgridClient, { ClientRequest } from '@sendgrid/client'
const sendgridRequest: ClientRequest = { /* ... */ }
await sendgridClient.request(sendgridRequest);
I wasn't able to test this because this module doesn't seem import into the typescript playground but I think that should work.