typescript - 打字稿变量存在检查
问题描述
考虑以下代码:
let str: string | null;
function print(msg: string) {
console.log(msg);
}
print(str);
在这种情况下,打字稿编译器给我一个错误,正确地说出类型为'string | null' 不能分配给“字符串”类型的参数。
这可以简单地固定检查str存在,所以
let str: string | null;
function print(msg: string) {
console.log(msg);
}
if (str) {
print(str);
}
编译没有错误。Typescript 编译器我足够聪明,可以理解检查。
现在假设您检查方法中是否存在变量,例如
let str: string | null;
function print(msg: string) {
console.log(msg);
}
function check(str: string) {
return str != null;
}
if (check(str)) {
print(str);
}
在这种情况下,打字稿不明白对print方法的调用是安全的。我怎样才能解决这个问题?
编辑
需要明确的是,这(或多或少)是我班的骨架:
好的,但我的情况有点复杂。这或多或少是我班级的结构:
class Clazz {
private myProp: {
aString?: string
anotherString?: number
};
constructor(aParam: any) {
this.myProp = {};
if (aParam.aString) {
this.myProp.aString = aParam.aString;
}
if (aParam.anotherString) {
this.myProp.anotherString = aParam.anotherString;
}
}
public haveAString() {
return this.myProp.aString != null;
}
public haveAnotherString() {
return this.myProp.anotherString != null;
}
public computation1() {
if (this.haveAString()) {
this.doAComputation(this.myProp.aString);
}
}
public computation2() {
if (this.haveAnotherString()) {
this.doAComputation(this.myProp.anotherString);
}
}
private doAComputation(str: string) {
// do something with the string
}
}
我应该如何解决我的情况?
解决方案
编译器不会跨函数边界进行检查,但您可以使用自定义类型保护来实现相同的效果
let str: string | null;
function print(msg: string) {
console.log(msg);
}
function check(str: string| null) : str is string{
return str != null;
}
if (check(str)) {
print(str);
}
推荐阅读
- javascript - 如何使用 CSS 标签作为选择器来选择某个元素/元素块?
- html - html中的li偏移量错误
- vbscript - 取消使用 ExecNotificationQuery 创建的 WMI 事件通知
- flutter - Flutter:尝试在加载之前显示奖励视频广告会破坏它
- sql-server - 我们可以在 SQL Server 中同时创建多少个数据库?
- javascript - Angular DI (injector.get(FooService))
- python - Scrapy - 找不到 xpath 元素
- excel - 如何避免第一个逗号和框出希望的范围
- android - 在 Android 中重置内容视图
- flutter - 如何使用 android_intent 包启动另一个应用程序?