8

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?

2 Answers 2

7

Another way of doing this in the absence of the original types:

method: 'PUT' as const,

A string is not assignable to HttpMethod, but the string literal 'PUT' is!

More details: https://stackoverflow.com/a/66993654/91713

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.