I have a custom interface that extends node:http2's IncomingHttpHeaders to allow custom header names to be added to an object.
However, no matter where I use such interface, TypeScript will complain that Object is possibly undefined, even though I have explicitly defined the types without null-ish values.
types.d.ts
import type { IncomingHttpHeaders } from "node:http2";
export interface CustomHeaders extends IncomingHttpHeaders {
[key: string]: string | string[] | undefined;
}
export type Result = {
request: {},
response: {
// ...
headers: CustomHeaders // definitely NOT undefined
}
};
do-something.ts
import type { CustomHeaders, Result } from "./types";
function doSomething(result: Result): Promise<Result> {
// ...
// (property) headers?: CustomHeaders | undefined <-- Why is there " | undefined" if the type "Result.response.headers" never specifies it?
result.response.headers["x-custom-header"] = "custom_value";
// ^^^^^^^ Object is possibly 'undefined'.ts(2532)
// 'headers' though, is definitely, never undefined ...
return Promise.resolve(result);
}
How do I properly type the interface CustomHeaders?