Search code examples
typescriptprismahashids

NumberLike safely convert it back to a number


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)


Solution

  • 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);