类型 { [键:字符串]:字符串 } 不可分配给类型 { [键:字符串]:字符串 } | 'undefined'



我正试图通过添加一个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定义了自己的类型,这些类型与确定性类型定义不兼容(node-fetch的可能是最新的(。如果两者都可用,则通常应该使用库自己的类型,而不是绝对类型。

https://github.com/node-fetch/node-fetch/blob/master/@类型/索引.d.ts#L60https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node-fetch/index.d.ts#L48

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

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

最新更新