【问题标题】:Type { [key: string]: string } is not assignable to type { [key: string]: string } | 'undefined'类型 { [key: string]: string } 不可分配给类型 { [key: string]: string } | '不明确的'
【发布时间】:2021-04-10 10:09:31
【问题描述】:

我正在尝试创建一个函数,只需添加一个 cookie,即可将 fetch 从 node-fetch 包装起来:

import fetch from 'node-fetch';

const api = (path: string, params: RequestInit) => fetch(
  path, {
    ...(params || {}),
    headers: {
      ...(params?.headers || {}),
      cookie: 'mycookie'
    },
  }
)

我在headers 收到此错误:

(property) RequestInit.headers?: string[][] | Headers | {
    [key: string]: string;
} | undefined
Type '{ cookie: string; append(name: string, value: string): void; delete(name: string): void; get(name: string): string | null; has(name: string): boolean; set(name: string, value: string): void; forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: any): void; } | { ...; } | { ...; }' is not assignable to type 'string[][] | Headers | { [key: string]: string; } | undefined'.
  Type '{ cookie: string; append(name: string, value: string): void; delete(name: string): void; get(name: string): string | null; has(name: string): boolean; set(name: string, value: string): void; forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: any): void; }' is not assignable to type 'string[][] | Headers | { [key: string]: string; } | undefined'.
    Type '{ cookie: string; append(name: string, value: string): void; delete(name: string): void; get(name: string): string | null; has(name: string): boolean; set(name: string, value: string): void; forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: any): void; }' is not assignable to type 'undefined'.ts(2322)

最后它说它不能分配给类型“未定义”。我想如果一个类型的值保证是它的联合类型之一,它不应该抱怨。

【问题讨论】:

  • 这些方法似乎让 typescript 出错了。

标签: javascript node.js typescript types


【解决方案1】:

node-fetch 定义了自己的类型,这些类型与 DefinitiveTyped 类型定义不兼容(node-fetch 可能是最新的)。如果两者都可用,您通常应该使用库自己的类型而不是 DefinedTyped。

https://github.com/node-fetch/node-fetch/blob/master/@types/index.d.ts#L60 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node-fetch/index.d.ts#L48

库的类型具有RequestInit 的body 属性为BodyInit | null,因此将其签名为null 的能力使其与其他类型不兼容。只需导入即可使用库的类型:

import fetch, { RequestInit } from 'node-fetch';

【讨论】:

    猜你喜欢
    • 2021-09-26
    • 1970-01-01
    • 2020-07-05
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多