Skip to content
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

Unary negation on an object should be a type error #57154

Closed
danvk opened this issue Jan 24, 2024 · 2 comments
Closed

Unary negation on an object should be a type error #57154

danvk opened this issue Jan 24, 2024 · 2 comments

Comments

@danvk
Copy link
Contributor

danvk commented Jan 24, 2024

🔎 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

https://www.typescriptlang.org/play?ts=3.3.3#code/MYewdgzgLgBCBGArGBeGBvAHgLhgRgBoYBPXAJgF8BuAKFElgAcAbAVwlRgGoFFb7oMALYBLMO04BaXv3AQQzAKYA6ZiADmAChbsio8RACUVGDAD0ZmADkAhlaK2rNIA

💻 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.

@MartinJohns
Copy link
Contributor

Duplicate of #20131. Used search terms: unary in:title

@danvk
Copy link
Contributor Author

danvk commented Jan 24, 2024

It's an oldie! It makes sense that this is less clear-cut than I thought because of Date and libraries like math.js.

Can't believe the word "negation" didn't appear anywhere in that issue!

@danvk danvk closed this as completed Jan 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants