网站搜索

TypeScript 变量存在性检查


考虑以下代码:

let str: string | null;

function print(msg: string) {
    console.log(msg);
}


print(str);

在这种情况下,TypeScript 编译器给了我一个错误,正确地指出 类型为 'string | null' 的参数不能分配给类型为 'string' 的参数。

这可以通过检查 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);
}

在这种情况下,TypeScript 无法理解对 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
    }

}

在我的情况下我应该如何处理?

答案#1

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

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