Checking whether a passed type is a literal type in TypeScript

35 Views Asked by At

In some type definition, I am interested in knowing whether a type parameter is number or a literal type:

type FixedArray<N extends number, T> =
    IsLiteralType<N> extends true ? ... : T[]

How can I know that? How can I implement IsLiteralType?

1

There are 1 best solutions below

0
Jean-Philippe Pellet On BEST ANSWER

Just found out this can be done like this: you can check whether a type is exactly another type by checking whether they both extend each other. So one extends clause will usually be in the constraints of the type parameter, and the reverse one can be in a conditional type.

So the example above can be done as follows (albeit with reversing the resulting type since the condition will be reversed as well):

type FixedArray<N extends number, T> =
    number extends N ? T[] : ...