在Typescript中检查变量是否存在

时间:2016-10-05 10:31:22

标签: typescript tslint

我正在使用TSlint(v3.15.1)和typescript(2.0.3)的更新版本更新旧的.ts文件。我得到了一些我想解决的错误。

代码是对某些类属性的简单存在性测试:

export class myClass {
    private pUserName: string;
    private pUserPass: string;
    private pHost: string;
    private pPort: number;

constructor($host: string, $port: number) {
    this.pHost = $host;
    this.pPort = $port;
}   

public isReady(): boolean {
        return Boolean(this.pUserName && this.pUserPass && this.pJiraHost && this.pJiraPort);
}

要么我得到“[ts]找不到名字布尔”,要么“无法将字符串转换为布尔值”......

我对打字稿很新,你能帮我找到正确的写法吗?

2 个答案:

答案 0 :(得分:0)

我发现了这种解决方法,它没有报告任何错误。然而,这是冗长而不是非常优雅...任何更好的主意? :)

public isReady(): boolean {
    for (const property in ['pUserName', 'pUserPass', 'pHost', 'pPort']) {
        if (typeof(property) !== 'string') {
            return false;
        }
    }
    return true;
}

答案 1 :(得分:0)

我还发现不包括es6定义类型:

现在我的tsconfig.json看起来像:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "ES6",
        "outDir": "out",
        "noLib": true,
        "sourceMap": true,
        "removeComments": true
    },
    "include" : [
        "node_modules/typescript/lib/lib.es6.d.ts",
        "node_modules/@types/node/index.d.ts",
        "node_modules/@types/q/index.d.ts",
        "node_modules/@types/mocha/index.d.ts",
        "node_modules/@types/moment/index.d.ts"
    ],
    "exclude": [
        "node_modules"
    ]
}