#Resolving type -1 for -(1)

19 messages · Page 1 of 1 (latest)

fallow lintel
#

Quick question, if I define a type as type Sign = 1 | -1 , then const num: Sign = -1 works but const num: Sign = -(1) fails the typing check. Is there no way for typescript to determine that -(1) is actually matching the type?

lucid fog
#

you are applying the unary - operator on a number, which will result in a number

#

and number is not assignable to 1 | -1

#

makes total sense from a type point of view

lucid fog
#

@fallow lintel

#

just because we seem to have all the necessary information at compile time doesn't mean you should compute all the types as narrow as possible, it's usually not necessary and current types should work well enough in most cases

fallow lintel
#

I see. I'm dealing with a lot of flipping for which I use 1 and -1 values. But slapping a - in front of a function that returns a Sign type will break the typing. Makes sense that the operation is at runtime and beyond the scope of typescript. I guess I'll just stick to number.

#

Thanks for the explanation!

lucid fog
#

hum, you could also use a boolean, an enum

#

or branded types

#

or some other techniques

#

idk how much typesafety you want or how much "clutter" you are willing to add to your code to have a more consitent solution

unborn shale
#

In this case you'd probably just have to make a utility function and put a cast in:

type Sign = -1 | 1;

const negate = (sign: Sign) => -sign as Sign;
#

Whether that's worth it or not is up to you, I guess.

#

I guess a lookup object is a type-safe approach too:

const negate: Record<Sign, Sign> = { [-1]: 1, [1]: -1}
fallow lintel
#

I haven' t heard of branded types before, I want to read into that.
I don't want to introduce boolean conversion to true -> 1 and false -> -1 or something alike, and I'd like to keep the ability to do multiplication with the Sign to other numbers.
I thought it would be nice to ensure that my variable is always a 1 or -1, and not accidentally any other number. But yeah its a balance of how much extra cluther to add.

#

I' ll consider these options, thanks! Have to toy around a bit with it

#

!resolved