typescript - 为什么这段代码不能用 typescript 编译?

标签 typescript

为什么这一段在下面的例子中编译不通过?

"|| this.greeting != "test2""

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    setGreeting(g) {
        this.greeting = g;
    }
    test() {
        if(this.greeting != "test" || this.greeting != "test2"){ 
            //this.greeting cound still be test3
        }
    }
}

Link to example

最佳答案

这实际上是一个有效的错误,可以防止您犯错。

if (this.greeting != "test" || this.greeting != "test2") { 

因为您使用的是 ||,所以第二个条件不会被执行,除非 this.greeting == 'test'。< br/> 现在,typescript 足够聪明,可以在进入第二个条件 block 时自动将 this.greeting 键入为 'test'

很明显,'test' != 'test2' 永远不会为假,检查该条件可能是错误的,因为您的整个 if 语句将 < em>总是返回真。

你可能想写:

if (this.greeting != "test" && this.greeting != "test2") {

关于typescript - 为什么这段代码不能用 typescript 编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45179995/

相关文章:

angular - 扩展已注入(inject)服务的类而不在子类中重复注入(inject)器?

typescript - 升级到 Typescript 2.9.1 后出现 "TS2300: Duplicate identifier ' 帐户错误

angular - 找不到模块 '@angular-persian/material-date-picker' 或其对应的类型声明

typescript - Angular 2找不到文件名 'Set'

node.js - Rollup 不捆绑声明文件

typescript - 在 Typescript 中导出和发布所有类型和接口(interface)

javascript - 传递给新 map 的二维数组在 typescript 中失败

javascript - 如何将 Vue 插件发布到 NPM?

angular - 在模型类 Angular 中注入(inject)服务

angular - 展开运算符执行次数超过预期