Multiplying by negative 1 in TypeScript + React

Viewed 27

I have some state variable

const [sortDirection, setSortDirection] = useState<1 | -1>(1);

I have a button which can modify the state variable like so

setSortDirection(sortDirection * -1);

However I get the warning

Argument of type 'number' is not assignable to parameter of type 'SetStateAction<1 | -1>'

How should I go about implementing this functionality? The sortDirection can only ever be -1 or 1, and multiplying by -1 should also adhere to that rule.

Of course I'm also open to other implementations, I don't need to have sortDirection: 1 | -1.

1 Answers

Typescript can't infer that sortDirection * -1 will always be 1 | -1

But you can do following :

setSortDirection(sortDirection > 0 ? -1 : 1);

Playground

Anyway, you will be better off using a boolean instead of this 2-state number.

Related