I can't wrap my head around why the following TypeScript code fails while seemingly everything should be ok:
interface Base { basic: boolean };
interface Super { basic: boolean; extra: boolean };
type Options<T> = T extends Super ? { isSuper: boolean } : { notSuper: boolean }
const baseOptions: Options<{ basic: boolean }> = { notSuper: true }; // ok
const superOptions: Options<{ basic: boolean; extra: boolean }> = { isSuper: true }; // ok
type MakeOptions = <T>() => Options<T>
function withOptions <T>(makeOptions: MakeOptions): void {
const options = makeOptions<T>();
console.log(options.notSuper); // Error: Property 'notSuper' does not exist on type 'Options<T>'.(2339)
console.log(options.isSuper); // Error: Property 'isSuper' does not exist on type 'Options<T>'.(2339)
}
I expect options.isSuper
to be undefined | { isSuper: boolean }
and options.notSuper
to be undefined | { notSuper: boolean }
Instead Typescript removes these properties alltogether.
Problem is solved when changing to
type Options<T> = T extends Super ? { isSuper: boolean; notSuper?: undefined } : { notSuper: boolean; isSuper?: undefined }
But it seems unnecessary.