Operator '==' cannot be applied to types x and y in Typescript 2

后端 未结 4 1007
梦谈多话
梦谈多话 2020-12-10 00:59

TypeScript Version: 2.0.2.0

Code I know the code is a bit stupid, but I actually have these kind of tests in my code (m

4条回答
  •  萌比男神i
    2020-12-10 01:20

    Faced the same issue in a scenario as the following:

    let a: string;
    
    a === 'some-value1' && a === 'some-value2';  // <==
    

    The second line produces the same error and maybe because Typescript is smart enough to know that a string type at a given moment cannot contain two (or more) different string literals.

    The correct approach for the above expression would be to use OR in the expression:

    a === 'some-value1' || a === 'some-value2';  // works fine :)
    

提交回复
热议问题