In the following code, why does the function notWorking pass TypeScript compilation, but the function working fails with:
error TS2353: Object literal may only specify known properties, and 'x' does not exist in type 'AAA'.
(Incidentally, notWorking does break compilation if I remove the property AAA.A - why?)
interface AAA {
A: number;
B?: number;
}
function notWorking(vals: number[]): AAA[] {
// No typescript error!
return vals.map(v => ({A: v, x: 'bad!'}));
}
function working(vals: number[]): AAA[] {
// error TS2353
return vals.map((v): AAA => ({A: v, x: 'bad!'}));
}
{A: v, x: 'bad!'}does satisfyAAA- excess property checks are only applied in certain circumstances, when the value can only ever be accessed via one interface, like (as your example shows) when there's an explicit return type.AAA["A"]then it's a different error, there are no properties in common -{ B?: number }compared to{ A: number; x: string }is strictly compatible but doesn't really make sense.