microsoft / microsoft/TypeScript
Additive inverse of number literals
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Search Terms
Using unary minus on variable that is of number-literal type. Negative number literals.
Suggestion
This is a specific case of #26382. My proposal is simply that if we apply unary minus on an expression whose type is a union of number literal types, the result should be a union of their additive inverses:
declare var a: 1 | 2 | 3;
const b = -a; // should be -1 | -2 | -3
Furthermore we could add a unary minus type operator:
-(42) === -42
-(A | B) === -A | -B
-number === number
-(not number) // error
Both should be very easy and uncontroversial to implement.
Use Cases
function compare(a: C, b: C): -1 | 0 | 1;
function reverseCompare(a: C, b: C): -1 | 0 | 1
{
return -compare(a, b); // shouldn't throw an error
}
The type operator would be just for sake of completeness
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing the related proposal in issue #26382 and the type-checking behavior for unary minus on number-literal unions. Done means the examples infer -1 | -2 | -3 and reverseCompare is accepted, while invalid non-number operands remain errors; no source files or tests are named in the issue.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100