Reputation: 21380
in following code with strictNullChecks
turned on I'm getting an error
Object is possibly 'undefined'.
class Smth {
private data: Array<{ value: number} | undefined> = [];
public doSmth(i: number) {
const data = this.data;
return data[i] && data[i].value === 0
// ^^^^^^^ Object is possibly 'undefined'.
}
}
I can't understand how it can be undefined after a check.
Upvotes: 4
Views: 313
Reputation: 32146
This is a known issue in Typescript.
TL;DR of that issue, Typescript can make these checks but the devs have chosen not to due to a significant performance cost on the compiler.
The workaround is to use the non-null assertion operator (!
) to tell the compiler that the value is not null
or undefined
. For this example:
return data[i] && data[i]!.value === 0
Upvotes: 1