SendGrid 客户端打字稿错误:HttpMethod

Sha*_*oon 5 javascript node.js sendgrid typescript sendgrid-api-v3

我有:

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);
Run Code Online (Sandbox Code Playgroud)

但是我的 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'.
Run Code Online (Sandbox Code Playgroud)

有没有办法解决这个问题?

jke*_*eys 7

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

method: 'PUT' as const,
Run Code Online (Sandbox Code Playgroud)

字符串不可分配给 HttpMethod,但字符串文字“PUT”可以!

更多详细信息:/sf/answers/4689555811/


Ale*_*yne 4

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'
                }
            }
        ]
    }
})
Run Code Online (Sandbox Code Playgroud)

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

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

const sendgridRequest: ClientRequest  = { /* ... */ }
await sendgridClient.request(sendgridRequest);
Run Code Online (Sandbox Code Playgroud)

我无法测试这个,因为这个模块似乎没有导入到打字稿游乐场中,但我认为这应该可行。