I would expect that value.length to be always defined by the time it reaches the .map operator. But using strictNullChecks with typescript throws the error "Object is possibly 'undefined'." Am I wrong, or is this a known issue?
this.count$ = this.store.select<Model>('state')
.filter(value => !!value && !!value.prop)
.map(value => value.prop)
It would only be defined if you provide some sort of initial value in your NGRX reducer. It can potentially be undefined if you haven't done that.
If you are dealing with arrays, then you want to set your initial value to []:
const initialState = [];
export function myReducer(state = initialState, action: Action)
....
The TypeScript compiler is correct, you could potentially have an undefined value if you haven't defined something somewhere.
EDIT
I think you are right in that the compiler isn't accurately detecting null values. If I turn on strictNullChecks and do the following, it works fine:
arr: Person[] = [];
ngOnInit() {
this.arr
.filter(x => !!x && !!x.firstName)
.map(x => console.log(x.firstName));
}
In fact, if I remove the filter, it still compiles without error. If I add this.arr.push(<Person>{lastName: 'test'}); it still compiles without error even though I never defined firstName on the object and thus it will be undefined.
If I remove the signature on arr then I get compiler errors that x.firstName is not defined.:
arr = [];
ngOnInit() {
this.arr
.filter(x => !!x && !!x.firstName)
.map(x => console.log(x.firstName));
}
So the TypeScript compiler with strictNullChecks checks whether fields exist on an object interface, but not necessarily whether they are defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With