microsoft / microsoft/TypeScript
Unary minus on 'any' should infer type to 'number | bigint', not just 'number'
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
🔎 Search Terms
"unary minus", "negate bigint"
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about bigint
⏯ Playground Link
💻 Code
const b = -(1n);
// ^?
const b2 = -b;
// ^?
const n = -(1);
// ^?
const n2 = -n;
// ^?
const a: any = b;
// ^?
const x = -a;
// ^?
const conv = (v: any) => -v;
// ^?
const r = conv(b);
// ^?
const conv2 = (v: number | bigint) => -v;
// ^?
const r2 = conv2(b);
// ^?
🙁 Actual behavior
Applying an unary minus on an any variable infers the type to number (as can be seen in the "hat-question mark" comments or the .D.TS tab for x, conv, and r). The inferred type for the constants x and r is thus wrong (they actually contain a BigInt value).
Unary minus on a number correctly infers number, and (more importantly) unary minus on a bigint correctly infers bigint. Same for unary minus on a number | bigint which infers number | bigint.
🙂 Expected behavior
Applying an unary minus on an any variable should infer the type to number | bigint.
ECMAScript specifies (https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-unary-minus-operator) unary minus as doing a ToNumeric (which returns either a Number of a BigInt) and then applying the appropriate unaryMinus abstract operation depending on the type of the value. The result is thus either a Number or a BigInt.
(the unary plus operator however converts to Number values only)
Additional information about the issue
No response
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 with the linked TypeScript Playground and reproduce the inferred types for unary minus on any, number, bigint, and number | bigint. Trace the compiler's handling of unary-minus type inference and its related tests; done means any-valued unary minus is inferred as number | bigint while the existing number and bigint behavior remains correct.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 38/100