Closed
Description
🔎 Search Terms
- unary negation object
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________
This is the behavior for TS 3.3, TS 5.3 and presumably all other versions.
⏯ Playground Link
💻 Code
const obj = {x: 1, y: 2};
const plus = +obj; // ok!?
const minus = -obj; // ok!?
console.log(plus, minus); // NaN, NaN
🙁 Actual behavior
No type errors, logs NaN, NaN
.
🙂 Expected behavior
I'd expect both +obj
and -obj
to be type errors. Applying unary negation or unary plus to an object is likely an error and produces a useless result.
Additional information about the issue
Thanks to JavaScript's coercive behavior around operators, I believe this is interpreted the same as -Number(obj)
and Number(obj)
is NaN
. Maybe that should be a type error, too, but the unary operators seem more clear-cut.
Using binary operators (obj + obj
) is already a type error, like you'd expect.
I ran into this in real code today when I refactored a type from:
- type Value = number;
+ type Value = number | { currency: '$' | '€'; value: number; };
I had code like -value
elsewhere and was surprised that I didn't get a type error.
Metadata
Metadata
Assignees
Labels
No labels