SendGrid client TypeScript Error: HttpMethod

SendGrid client TypeScript Error: HttpMethod

我有:

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);

但是我的 TypeScript 语言服务器给我一个关于 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'.

有什么办法可以解决这个问题吗?

您的对象中的

method: 'PUT' 被推断为 string,但它需要特定的字符串,例如 "PUT" | "GET" | "POST"。这是因为它没有要尝试匹配的特定类型,并且默认情况下特定字符串只是推断为 string.

您可能可以通过将对象直接传递给函数来解决此问题。这会将对象转换为正确的类型,因为它会根据该函数接受的内容进行检查:

await sendgridClient.request({
    method: 'PUT',
    url: '/v3/marketing/contacts',
    body: {
        list_ids: [myId],
        contacts: [
            {
                email: req.body.email,
                custom_fields: {
                    [myFieldId]: 'in_free_trial'
                }
            }
        ]
    }
})

或者您可以为您的中间变量提供从 sendgrid 模块导入的正确类型。

import sendgridClient, { ClientRequest } from '@sendgrid/client'

const sendgridRequest: ClientRequest  = { /* ... */ }
await sendgridClient.request(sendgridRequest);

我无法测试这个,因为这个模块似乎没有导入 typescript playground 但我 认为 应该可以工作。

另一种在没有原始类型的情况下执行此操作的方法:

method: 'PUT' as const,

字符串不可分配给 HttpMethod,但字符串文字 'PUT' 是!

更多详情: