-1

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!'}));
}
6
  • 2
    Because {A: v, x: 'bad!'} does satisfy AAA - 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. Commented Dec 3 at 11:19
  • Excess property checks are only applied directly, like in the second example. Not indirectly, like in the first Commented Dec 3 at 11:19
  • Or e.g. stackoverflow.com/q/54445577/3001761, stackoverflow.com/q/53858029/3001761, ... Commented Dec 3 at 11:21
  • And if you remove 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. Commented Dec 3 at 11:30
  • "(Incidentally, notWorking does break compilation if I remove the property AAA.A - why?)" Seems like perfectly reasonable behaviour - if you have an object of one shape and try to use an object with absolutely incompatible shape as it, then the compiler stops you. I really can't think of any reason you'd want that to compile. It seems like code like this would be a mistake the vast majority of times it's encountered. And in the exceptionally rare occasions where you probably do want that code, well, it'd be an exception tot he otherwise reasonable behaviour. Commented Dec 3 at 11:30

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.