-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Unable to use !== on union types with a string literal types #11277
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
This is working as intended. The error in the first example is reported because the control flow analyzer knows that the actual type of function foo(f: 'none' | Color) {
f !== 'none'; // Ok
} Here the comparison is ok because the control flow analyzer only knows the declared type for If you really want a const None: 'none' | Color = 'none'; Alternatively, you can use the expression |
@ahejlsberg Isn't it the wrong assumption of control flow analyzer about actual type of Consider: class Color {
constructor(public r: number, public g: number, public b: number) {
}
}
var f: 'none' | Color = new Color(0, 0, 0);
function test() {
f = 'none'
}
test()
f !== 'none'; |
@wallverb Effects of assignments in nested functions is an orthogonal issue. We currently don't account for them, and given the first class nature of functions we'll never be able to completely analyze such side effects without being overly conservative. There have been many discussions on this topic and #9998 summarizes where we are. |
Thank you @ahejlsberg . Great discussion |
This feature is catching common logic errors and forcing people to write cleaner code that has fewer redundant conditionals. It's absolutely fantastic. |
TypeScript Version: 2.0.3
Code
Expected behavior:
No errors
Actual behavior:
error TS2365: Operator '!==' cannot be applied to types 'Color' and 'string'.
If the tested variable is a member of an object, the above code works:
The text was updated successfully, but these errors were encountered: