How to create dynamic number union in typescript

Hey guys, so I'm starting to think this isn't even possible (especially with the comments chatGPT added saying its not possible lol)

so basically I have a function, which im going to call 'test'

test receives a generic that is expected to be a union type. We will call this type R

For the return type of 'test', it is sending back a tuple. This tuple consists of 2 objects of 2 different types.

[R, X]


Essentially, I need help solving for X. I need X to be a union type of numbers starting at 0 and incrementing until the length of the unions are equal.

Is there any way to potentially accomplish this? It is in essence the final thing I need to complete the little project I've been working on today which is just a 'better' enum


type Role = 'User' | 'Admin' | 'Owner';
type RoleNum = 0 | 1 | 2;

//In the first example here, we are defining a 'Role' type and a generic R.  Ideally we would be able to break down the union type passed into R to create the 'RoleNum' type.  Instead of parameters, the data is passed in directly as the type. 
function test<R extends string>(): [Record<R, number>, RoleNum]  {
  //const [first, ...rest] = params;
  //const enumerated = typeof first === 'boolean' ? first : undefined;
  const result = {} as Record<R, number>;
  const unionType: number[] = [];


  return [result, unionType];
}



//In this example, we nix the R type all together and pass in the hard coded string values.  This could be better because it includes an array that can be iterated through
function test(...role: string[] ): [Record<R, number>, RoleNum] {
  //const [first, ...rest] = params;
  //const enumerated = typeof first === 'boolean' ? first : undefined;
  const result = {} as Record<R, number>;
  const unionType: number[] = [];


  return [result, unionType];
}
Was this page helpful?