Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if type is a 'string' literal, 'number' literal or 'string | number' literal

Tags:

typescript

Since the typescript now supports conditional types, I've decided to do some meta-programing to add more flavor to VSCODE intellisense. However, while other types are easy to separate using A extends B I have a hard time determining if the provided type is literal.

So the question would be - how do I determine if given type is of literal type?

like image 351
FrogTheFrog Avatar asked Oct 21 '25 05:10

FrogTheFrog


1 Answers

I'm not sure what your use cases are. Personally, I would do something like this:

type IfStringOrNumberLiteral<T, Y=true, N=false> =
  string extends T ? N : // must be narrower than string
  number extends T ? N : // must be narrower than number
  [T] extends [never] ? N : // must be wider than never
  [T] extends [string | number] ? Y : // must be narrower than string | number
  N

I always use --strictNullChecks so your mileage may vary when it comes to how that treats null and undefined. Of course it can be amended to meet any particular need you have. Mostly I just wanted to show an alternative to circuitous constructs of the form ( X extends Y ? true : false ) extends true ? U : V.

Hope that helps; good luck.

like image 155
jcalz Avatar answered Oct 23 '25 19:10

jcalz