Skip to content

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

Closed
@danvk

Description

@danvk

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions