You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
constobj={x: 1,y: 2};constplus=+obj;// ok!?constminus=-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.
The text was updated successfully, but these errors were encountered:
🔎 Search Terms
🕗 Version & Regression Information
This is the behavior for TS 3.3, TS 5.3 and presumably all other versions.
⏯ Playground Link
https://www.typescriptlang.org/play?ts=3.3.3#code/MYewdgzgLgBCBGArGBeGBvAHgLhgRgBoYBPXAJgF8BuAKFElgAcAbAVwlRgGoFFb7oMALYBLMO04BaXv3AQQzAKYA6ZiADmAChbsio8RACUVGDAD0ZmADkAhlaK2rNIA
💻 Code
🙁 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)
andNumber(obj)
isNaN
. 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:
I had code like
-value
elsewhere and was surprised that I didn't get a type error.The text was updated successfully, but these errors were encountered: