NumberLike safely convert it back to a number

252 Views Asked by At

I am using Hashids, and they have the following type:

export declare type NumberLike = bigint | number;

When I try to use it on Prisma, I get an error because id is not a number

const id = hashids.decode(handler)

How can I safely convert it back to a number?

  const entry = await prisma.entry.findUnique({
    where: {
      id: id, // Type 'NumberLike[]' is not assignable to type 'number'.ts(2322)
    },
  })

Type 'NumberLike[]' is not assignable to type 'number'.ts(2322)

2

There are 2 best solutions below

0
On BEST ANSWER

NumberLike can be converted into a number using the Number() function.

const id :number = Number(hashids.decode(hash)[0]);

(we use [0] to grab the first number because decode returns an array)

Or, if you encoded an array of numbers:

const ids :number[] = hashids.decode(hash).map(Number);
0
On

As long as you haven't hashids.encode()-ed an array you could simply add + before decoding it and it will be reduced to just a number

let encodedId = hashids.encode(123);
let decodedId = +hashids.decode(encodedId); // this is now of type number