Skip to content

Useless compile error on triple-equal 1|2 against 0 #21724

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

Closed
rogierschouten opened this issue Feb 7, 2018 · 3 comments
Closed

Useless compile error on triple-equal 1|2 against 0 #21724

rogierschouten opened this issue Feb 7, 2018 · 3 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@rogierschouten
Copy link

TypeScript Version: 2.7.1

Search Terms: infer, compare, equals

Code

type T = [number] | [number, number];  // now t.length has type 1|2
let t: T;
if (t!.length === 0) { // compile error: Operator '===' cannot be applied to types '1' and '0'
}
if (t!.length > 100) { // no compile error
}
if (t!.length === 1 - 1) { // no compile error
}

Expected behavior:
No compile errors on any of these. It's plain inconsistent and not useful.

Actual behavior:
Compile error on t === 0 but not on other comparisons

Playground Link:
See above

Related Issues:

@ghost
Copy link

ghost commented Feb 7, 2018

Tuples have a fixed length as of #17765. If you suspect that t could be a "tuple" of arbitrary length, you could simply use the type number[], since tuples are arrays.
It's true that we could give an error on t.length > 100 because all known lengths are less, but not sure if that would be worth the complexity to add. Same for evaluating constant expressions like 1 - 1; any arithmetic operation on numbers is just treated as a number for simplicity.

@ghost ghost added the Working as Intended The behavior described is the intended behavior; this is not a bug label Feb 7, 2018
@krryan
Copy link

krryan commented Feb 7, 2018

For what it's worth, I would love to see arithmetic constraints on things like lengths. But such an error only really becomes useful when users can write such constraints (I envision writing a function like f(valueThatIsNotEmpty: string & { length: number > 0; }) or something).

@typescript-bot
Copy link
Collaborator

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@microsoft microsoft locked and limited conversation to collaborators Jul 3, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

3 participants