I am facing an issue with an object that has conditional keys. For example:
const headers: RequestHeaders = {};
if (...) {
headers.foo = 'foo';
}
if (...) {
headers.bar = 'bar';
}
As a newcomer to TS, I initially thought this would work:
type RequestHeaders = {
foo?: string,
bar?: string,
};
However, when passing this to fetch
, the type definition for fetch
's headers is { [key: string]: string }
. This results in the error message:
Type 'RequestHeaders' is not assignable to type '{ [key: string]: string; }'.
Property 'foo' is incompatible with index signature.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
To make it work, I had to use
type RequestHeaders = { [key: string]: string };
. Is there a way to restrict the keys to a predefined set of strings?