I have:
JavaScript
x
22
22
1
import sendgridClient from '@sendgrid/client'
2
sendgridClient.setApiKey(process.env.SENDGRID_API_KEY);
3
4
const sendgridRequest = {
5
method: 'PUT',
6
url: '/v3/marketing/contacts',
7
body: {
8
list_ids: [myId],
9
contacts: [
10
{
11
email: req.body.email,
12
custom_fields: {
13
[myFieldId]: 'in_free_trial'
14
}
15
}
16
]
17
}
18
};
19
20
21
await sendgridClient.request(sendgridRequest);
22
But my TypeScript language server gives me an error about sendgridRequest
:
JavaScript
1
4
1
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'.
2
Types of property 'method' are incompatible.
3
Type 'string' is not assignable to type 'HttpMethod'.
4
Is there some way to resolve this?
Advertisement
Answer
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:
JavaScript
1
16
16
1
await sendgridClient.request({
2
method: 'PUT',
3
url: '/v3/marketing/contacts',
4
body: {
5
list_ids: [myId],
6
contacts: [
7
{
8
email: req.body.email,
9
custom_fields: {
10
[myFieldId]: 'in_free_trial'
11
}
12
}
13
]
14
}
15
})
16
Or you can give your intermediate variable the correct type imported from the sendgrid module.
JavaScript
1
5
1
import sendgridClient, { ClientRequest } from '@sendgrid/client'
2
3
const sendgridRequest: ClientRequest = { /* ... */ }
4
await sendgridClient.request(sendgridRequest);
5
I wasn’t able to test this because this module doesn’t seem import into the typescript playground but I think that should work.