Encountering an issue with object literal type.
interface OptionalFoo {
foo?: number;
}
interface Bar {}
function foobarFn(foobar: OptionalFoo & Bar) {}
foobarFn({ bar: 1 }); // error
foobarFn({ bar: 1 } as { bar: number }); // ok
foobarFn({ bar: 1 } as { bar: 1 }); // ok!
Running into a type error due to object literal with inferred type:
Argument of type '{ bar: number; }' is not assignable to parameter of type 'OptionalFoo & Bar'
The inference itself is not the root cause of the problem:
const bar = { bar: 1 }; // inferred { bar: number; }
foobarFn(bar); // ok!?
A similar issue arises with spread syntax vs Object.assign
:
foobarFn({...{ bar: 1 }}); // error
foobarFn(Object.assign({}, { bar: 1 })); // ok!?
Is there a way to achieve the desired behavior with inferred object literal type (excess property check) without using in-place object literals, such as through the use of a variable like bar
or a function call like Object.assign({ bar: 1 })
?