Consider the following code that tries to conditionally add a property to an object with an inferred type:
const foo = {
a: 1,
b: 2,
};
if (bar) {
foo.c = 3; // Error: Property 'c' does not exist on type '{ a: number; b: number; }'.(2339)
}
It's possible to remove the error by explicitly declaring the type of foo as { a: number; b: number; c?: number; } or using a spread to conditionally add c:
const foo = {
a: 1,
b: 2,
...(bar ? { c: 3 } : {}),
};
However, let's say we wanted to keep the original code structure but we also wanted to avoid having to explicitly declare properties that could be inferred. Are there any solutions that could satisfy both counts? For example, is it possible to somehow adjust the inferred type, something like:
const foo = {
a: 1,
b: 2,
} as { ...; c?: number; }; // Example, does not work