首页 > 解决方案 > 打字稿变量存在检查

问题描述

考虑以下代码:

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
    }

}

我应该如何解决我的情况?

标签: typescript

解决方案


编译器不会跨函数边界进行检查,但您可以使用自定义类型保护来实现相同的效果

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);
}

推荐阅读