TypeScript generic contraints with extending and default parameters
Type T
at the definition time is unknown, so the compiler throws this error that you cannot initialize something you are unaware of. There are a couple of workarounds I can think of, but not sure how useful they are for your case.
You can leave type T
as is, and use union types for the options
parameter as follows:
const test1 = <T> (options: T | { bar?: boolean } | { foo?: string } = { foo: '' }) => {
console.log(options);
};
Another workaround is to use a type assertion and manually tell the compiler that the initializer is of the type it needs to be:
const test2 = <T extends { foo?: string }>(options: T & { bar?: boolean } = { foo: '' } as T & { bar?: boolean }) => {
console.log(options);
};
But keep in mind that these are just workarounds and whenever you have to use a workaround, it implies a flaw in the design. Maybe you can take a second look at your logic and improve it in order to remove the need for these workarounds. Or maybe, you can skip argument initialization and add options.foo = options.foo || '';
as the first line of code in your function. Just some ideas.