Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Type 'number | null' is not assignable to type 'number'

Tags:

typescript

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?


2 Answers

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;
like image 60
Ryan Cavanaugh Avatar answered Sep 13 '25 13:09

Ryan Cavanaugh


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.

like image 22
Andreas Müller Avatar answered Sep 13 '25 13:09

Andreas Müller