【发布时间】:2020-12-14 06:15:39
【问题描述】:
考虑以下代码,它尝试有条件地将属性添加到具有推断类型的对象:
const foo = {
a: 1,
b: 2,
};
if (bar) {
foo.c = 3; // Error: Property 'c' does not exist on type '{ a: number; b: number; }'.(2339)
}
可以通过将foo 的类型显式声明为{ a: number; b: number; c?: number; } 或使用扩展有条件地添加c 来消除错误:
const foo = {
a: 1,
b: 2,
...(bar ? { c: 3 } : {}),
};
但是,假设我们希望保留原始代码结构,但我们也希望避免显式声明可以推断的属性。有没有可以同时满足这两个方面的解决方案?例如,是否可以以某种方式调整推断的类型,例如:
const foo = {
a: 1,
b: 2,
} as { ...; c?: number; }; // Example, does not work
【问题讨论】: