headers 'object is possibly undefined' with type extending node:http2's IncomingHttpHeaders

Viewed 26

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?

1 Answers

Your Result.response type has either optional properties values either required, as in your code:

export type Result = {
  request: {},
  response: {
    // ...
    headers: CustomHeaders // definitely NOT undefined
  }
};

If your properties are optional, then your doSomething function needs to do type check:

function doSomething(result: Result): Promise<Result> {
  
  if (typeof result.response !== 'undefined' && typeof result.response.headers !== 'undefined') {
     result.response.headers["x-custom-header"] = "custom_value";
  }

  return Promise.resolve(result);
}
Related