Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

typescript 中赋值时多种数据类型的问题

一个传入参数 handle 被声明为类型 a|null,然后将该参数赋值给类型为 a 的变量会报错,要如何解决?看下图
image
我应该将传入参数的类型指定为 a 而不要 a|null ??


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

代码中 SimpleReuseStragegy.snapshorts[key] 要求输入一个非空值,而 handle 的类型有可能是空,所以如果允许 SimpleReuseStragegy.snapshots[key] = handle 的话就有可能造成空异常(比如 SimpleReuseStragegy 在使用某个 snapshot 的时候以为它是非空的,但实际是空)。

所以从逻辑上来说,这个赋值应该更严谨一些,加上空判断

if (handle !== null) {  // 或者 if (!handle) ;在 DetacheRouteHandle 只可能是函数类型时可以这样简化
    SimpleReuseStragegy.snapshots[key] = handle;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...