我有以下代码:
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.
如何正确地将相似的数量分配给数字?
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)
| 归档时间: |
|
| 查看次数: |
3886 次 |
| 最近记录: |