3

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.

3
  • I do not understand, do you need to create a type from the type of the list? Commented Mar 23, 2022 at 16:45
  • AFAIK this is not possible; I have an issue about this still open Commented Mar 23, 2022 at 18:36
  • Tuple labels and function parameter names are essentially unobservable from the type system; they are only for documentation. The types (username: string, message: string, totalMessagesSent: number)=>void and (x: string, y: string, z: number)=>void are identical. Also, what exactly do you mean by "get arguments for a callback function"? Is this in a type? Or an actual function implementation? Commented Mar 23, 2022 at 23:16

1 Answer 1

1

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"]>
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for answering so quickly, but I have come to the conclusion that my wording in the question was incorrect. I am trying to use it as arguments in a callback function, and I am afraid that that might require a different solution. I updated the question with a more accurate description of my goal if you want to see it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.