【问题标题】:Check variables existence in Typescript检查 Typescript 中是否存在变量
【发布时间】:2017-02-13 18:11:06
【问题描述】:

我正在使用 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] 找不到名称布尔值”,要么是一些“无法将字符串转换为布尔值”......

我是打字稿的新手,你能帮我写一下正确的方法吗?

【问题讨论】:

    标签: typescript tslint


    【解决方案1】:

    我找到了这个解决方法,它不会报告任何错误。然而,这很冗长而且不是很优雅......有更好的主意吗? :)

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

    【讨论】:

    • 您可以使用return !!(this.pUserName && this.pUserPass && this.pJiraHost && this.pJiraPort); 注意 - 空字符串和零也会报告为false
    【解决方案2】:

    我还发现没有包含 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"
        ]
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-21
      • 2014-09-08
      • 2011-12-19
      • 2020-09-30
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      • 1970-01-01
      相关资源
      最近更新 更多