I have trouble understanding why TypeScript infers program.options here as ProgramAOptions | ProgramBOptions. Thus it cannot compile code since optA does not exist in ProgramBOptions. Can you explain or point me to documentation which explains this behaviour?
type ProgramName = 'a' | 'b';
type ProgramAOptions = {
optA: number;
};
type ProgramBOptions = {
optB: number;
};
type Program<T extends ProgramName> = {
name: T;
options: T extends 'a' ? ProgramAOptions : ProgramBOptions;
};name
function test(p: Program<ProgramName>) : void
{
if (p.name === 'a')
{
p.options.optA = 10; /* this line would not compile with error:
error TS2339: Property 'optA' does not exist on type 'ProgramAOptions | ProgramBOptions'.
Property 'optA' does not exist on type 'ProgramBOptions'.*/
}
}