javascript - 输入 { [键 : string]: string } is not assignable to type { [key: string]: string } | 'undefined'

标签 javascript node.js typescript types

我正在尝试创建一个函数,通过添加一个 cookie 从 node-fetch 包装 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)

最后它说它不能分配给类型“undefined”。我想如果一个类型的值保证是它的联合类型之一,它不应该提示。

最佳答案

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

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

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

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

关于javascript - 输入 { [键 : string]: string } is not assignable to type { [key: string]: string } | 'undefined' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65565679/

相关文章:

javascript - CSS TransitionEnd 未触发

node.js - Sequelize : "Cannot read property ' length' of undefined"

visual-studio - 仅当先前编译的 JavaScript 文件已被删除时,TypeScript 才会编译

typescript - 是否建议发布 TypeScript 节点模块的源文件?

javascript - 这是指向鹅毛笔编辑器工具栏

javascript - 鼠标悬停 mouseout JavaScript 不工作

javascript - 如何将 express.js 服务器部署到 Netlify

javascript - 有没有办法防止 neDB 集合数组中的条目重复?

javascript - 将 "import"与 Node 库一起使用,而不是 "require"?

typescript - 基于 Vue 类的组件警告 : Property is not defined on the instance but referenced during render