javascript - Tipo { [key: string]: string } no es asignable al tipo { [key: string]: string } | 'undefined'
Estoy intentando crear una función que envuelva fetch de node-fetch simplemente agregando una cookie:
import fetch from 'node-fetch';
const api = (path: string, params: RequestInit) => fetch(
path, {
...(params || {}),
headers: {
...(params?.headers || {}),
cookie: 'mycookie'
},
}
)
Estoy recibiendo este error en 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)
Al final dice que no se puede asignar al tipo 'undefined'. Pensé que si se garantiza que un valor para un tipo es uno de sus tipos de unión, no debería quejarse.
Respuesta #1
node-fetch define sus propios tipos que son incompatibles con las definiciones de tipos de DefinitelyTyped (los de node-fetch son presumiblemente más actualizados). Generalmente, deberías usar los propios tipos de una biblioteca en lugar de los de DefinitelyTyped si ambos están disponibles.
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
El tipo de la biblioteca tiene la propiedad body de RequestInit como BodyInit | null, por lo que la capacidad de asignarla como null la hace incompatible con el otro tipo. Utiliza el tipo de la biblioteca simplemente importándolo:
import fetch, { RequestInit } from 'node-fetch';
