[英]Typescript: Type 'number | null' is not assignable to type 'number'
我有以下代码:
let statistics = this.video.getStatistics();
let currentLikeCount : number = statistics!.getLikeCount() ? statistics.getLikeCount() : 1;
但是,使用 Typescript 编译时出现以下错误
error TS2322: Type 'number | null' is not assignable to type 'number'.
我的条件检查以查看喜欢计数是否为空,如果是,则将其分配给一个数字,但打字稿仍然抱怨它可能为空。
如何正确地将喜欢计数分配给一个数字?
TypeScript 无法知道每次调用getLikeCount()
返回相同的值。 还有很多其他方法可以以不调用函数两次的方式编写此代码,例如:
statistics.getLikeCount() || 1
或者
const c = statistics.getLikeCount();
let c2 = c == null ? c : 1;
只是为了澄清为什么编译器仍然抱怨:
如果你把三元语句写成 if/else,你会得到
if (statistics!.getLikeCount()) {
currentLikeCount = statistics.getLikeCount();
} else {
currentLikeCount = 1;
}
TS 编译器独立评估对getLikeCount()
的两次调用,因此会抱怨可能的空值。 瑞安的回答提供了解决这个问题的可能方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.