It is quite surprising that this snippet of typescript does not throw a type error, which you can also test in the typescript sandbox:
class Foo {
constructor(readonly x: number, readonly y: number) {}
}
const xOfFirstFoo = (arr: Array<Foo>): number => {
return arr[0].x
}
const result = xOfFirstFoo([]);
// The above line results in:
// [ERR]: "Executed JavaScript Failed:"
// [ERR]: Cannot read property 'x' of undefined
One would assume that the typer should recognize that arr[0]
(or any arr[i]
) could either be a Foo
or undefined
, and therefore it cannot guarantee the presence of an .x
property.
So, what's really happening here?