Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript map a list to function arguments

I have a list of arguments looking a little something like this:

const args: FeatureEventArg[] = [
  {
    name: 'username',
    type: 'string',
  },
  {
    name: 'message',
    type: 'string',
  },
  {
    name: 'totalMessagesSent',
    type: 'number',
  },
];

And my goal is to take that list and with some type, like FeatreEventArgs<typeof args> or something, to get arguments for a callback function that would end up looking something like this:

function callback(username: string, message: string, totalMessagesSent: number) {
  // Other stuff
}

I've managed to get the types part with a lot of fidelling and a lot of extends "string" ? string kinda thing. But the names are just arg_0 instead of the name in the object above.

Anyways, if you have any tips or ideas of how I can achieve this or any other solutions to the problem please let me know.

like image 989
JanuZz_dk Avatar asked Sep 12 '26 12:09

JanuZz_dk


1 Answers

You'll need to drop the : FeatureEventArg[] and instead interpret the array of objects as const so that the exact string types get preserved. Then you can map over the [number] values of the array, extracting the name as the key and the type as the value (through a helper type that transforms the string into the corresponding type).

const args = [
  {
    name: 'username',
    type: 'string',
  },
  {
    name: 'message',
    type: 'string',
  },
  {
    name: 'totalMessagesSent',
    type: 'number',
  },
] as const;
type Args = typeof args;
type ToPrimitive<T> =
    T extends 'string' ? string
  : T extends 'number' ? number
  : never;

type ArgsObj = {
  [T in Args[number] as T["name"]]: ToPrimitive<T["type"]>
}
like image 108
CertainPerformance Avatar answered Sep 15 '26 11:09

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!