I have the following code:
let statistics = this.video.getStatistics();
let currentLikeCount : number = statistics!.getLikeCount() ? statistics.getLikeCount() : 1;
However, I get the following error when compiling with Typescript
error TS2322: Type 'number | null' is not assignable to type 'number'.
My conditional checks to see if the like count is null, and, if so, assigns it to a number, but typescript still complains about it possibly being null.
How to I properly assign the like count to a number?
There's no way for TypeScript to know that getLikeCount()
returns the same value every time it's called. There are lots of other ways to write this code in a way that doesn't invoke the function twice, e.g.:
statistics.getLikeCount() || 1
Or
const c = statistics.getLikeCount();
let c2 = c == null ? c : 1;
Just for some clarification why the compiler still complains:
if you write the ternary statement as if/else, you get
if (statistics!.getLikeCount()) {
currentLikeCount = statistics.getLikeCount();
} else {
currentLikeCount = 1;
}
The TS Compiler evaluates the two calls to getLikeCount()
independently and thus complains about possible null values.
Ryan's answer provides possible ways to get around this.
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