I have an object with conditional keys. I.e.:
const headers: RequestHeaders = {};
if (...) {
headers.foo = 'foo';
}
if (...) {
headers.bar = 'bar';
}
I'm new to TS and I expected this to work:
type RequestHeaders = {
foo?: string,
bar?: string,
};
However, I'm passing this to fetch and the type definition for fetch's headers is { [key: string]: string }. I'm getting:
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'.
The only way I could get this to work is type RequestHeaders = { [key: string]: string };. Is there a way to limit the keys to a set of predefined strings?