4

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?

1
  • What's the type of getLikeCount ? Commented Sep 19, 2017 at 18:48

2 Answers 2

9

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;
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.