打字稿:输入'编号| null'不能分配给'number'类型

Ada*_*rax 2 typescript

我有以下代码:

let statistics = this.video.getStatistics();

let currentLikeCount : number = statistics!.getLikeCount() ? statistics.getLikeCount() : 1;
Run Code Online (Sandbox Code Playgroud)

但是,在使用Typescript进行编译时出现以下错误

error TS2322: Type 'number | null' is not assignable to type 'number'.
Run Code Online (Sandbox Code Playgroud)

我的条件检查以查看like count是否为null,如果是,则将其分配给一个数字,但typescript仍然抱怨它可能为null.

如何正确地将相似的数量分配给数字?

Rya*_*ugh 9

TypeScript无法知道getLikeCount()每次调用时返回相同的值.还有很多其他方法可以以不调用函数两次的方式编写此代码,例如:

statistics.getLikeCount() || 1
Run Code Online (Sandbox Code Playgroud)

要么

const c = statistics.getLikeCount();
let c2 = c == null ? c : 1;
Run Code Online (Sandbox Code Playgroud)