【发布时间】:2022-01-17 21:49:25
【问题描述】:
我很难理解为什么 TypeScript 将这里的 program.options 推断为 ProgramAOptions | ProgramBOptions。因此它无法编译代码,因为optA 在ProgramBOptions 中不存在。你能解释一下或指向我解释这种行为的文档吗?
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'.*/
}
}
【问题讨论】:
标签: typescript type-inference conditional-types