Using Typescript to transform a list into function arguments

My current challenge involves a set of arguments structured like so:

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

The objective is to transform this list using some type, possibly

FeatreEventArgs<typeof args>
, in order to generate arguments for a callback function that resembles the following:

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

I have managed to tackle the types aspect through various adjustments and enhancements such as

extends "string" ? string
. However, I am encountering difficulty with the names which currently present as arg_0 instead of the specified names within the object.

If you have any recommendations, suggestions, or alternative solutions to address this issue, please feel free to share your insights. Thank you!

Answer №1

To maintain the exact string types, it is necessary to eliminate the : FeatureEventArg[] and instead treat the array of objects as const. By doing so, you can iterate over the [number] values in the array, extracting the name as the key and the type as the value using a helper type that converts 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"]>
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering challenges while transitioning from ngrx version 2 to version 4, specifically related to typing in array de-structuring

The error indicates a missing comma after the action parameter in the .map. Another error pops up when hovering over DataActions.AddDataAction, displaying Tuple type '[Action, AppStore]' with length '2' cannot be assigned to tuple with ...

How can you prevent the keys from being read-only when mapping onto a type?

Here's a common query: How can I change keys from readonly to writable when using a type that is Readonly? For example: type Foo = Readonly<{ foo: number bar: number }> type Bar = /* What's the method to duplicate the Foo type, but w ...

Transmitting form data inputted by the user to a modal that resides in the same component, all without the need for child or parent components or

In need of a solution where users can input answers to questions and have all the entered data displayed in a popup alongside the respective question. If a user chooses not to answer a question, I do not want that question or any related information to be ...

Steps to fix the issue of 'Property 'foo' lacks an initializer and is not definitely assigned in the constructor' while utilizing the @Input decorator

What is the proper way to initialize a property with an @Input decorator without compromising strict typing? The code snippet below is triggering a warning: @Input() bar: FormGroup = new FormGroup(); ...

"Launching" conduit for Observable

Is there a way to attach two pipes to an HttpClient request in order to execute functions at the beginning and end of the request? I have discovered the "finalize" operator for executing a function when the request is finished, but I am looking for an equi ...

What are the drawbacks of introducing a dependency within the constructor?

I'm struggling to understand why breaking the rules is considered bad. import {DepClass} from './di-import' // <- some dependency imports here class DI1 { dep1: DepClass constructor(){ this.dep1 = new DepClass() // ...

What kind of function possesses additional attributes or characteristics?

I am finding it difficult to define the type for the function foo as demonstrated below: function foo() { do something } foo.boo = () => { do something else } foo("hello"); foo.boo("hello"); This JavaScript code is functioning corr ...

The sticky navbar fails to stay in place when the content becomes too lengthy

This is my current state of code (minified, for explanation only) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-w ...

A foundational NodeJS program in TypeScript featuring a structured client-utility-definition setup with adherence to stringent coding guidelines

What is the best way to set up a basic TypeScript framework for starting a program with strict settings, based on the following program structure? An initial "client" code containing the actual program logic A separate "utility" module for defining funct ...

Can a constant be utilized as the property name within routerLink when specifying queryParams?

I am currently trying to update the current page by modifying or adding the query parameter "categoryId". When I attempt: <a [routerLink]="" [queryParams]="{ categoryId: category!.id }" queryParamsHandling="mer ...

Guide to configuring a function to display the maximum value on a boxplot in Highcharts

I'm currently using Angular in combination with the highcharts boxplot API. While I am aware that I can manually set the max value of the y-axis in the chart configuration, such as: max: 100, tickInterval: 10. There's now a need for me to dynami ...

A guide on creating a concatenation function using TypeScript

Looking for a way in Typescript to define an interface Calculator that allows for concatenation capabilities? interface Calculator { ... } let calcu: Calculator; calcu(2).multiply(5).add(1) I attempted the following: interface Calculator { (num: n ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

Creating a View-Model for a header bar: A step-by-step guide

I am looking to develop a View-Model for the header bar using WebStorm, TypeScript, and Aurelia. In my directory, I have a file named header-bar.html with the following code: <template bindable="router"> <require from="_controls/clock"></ ...

Exploring the integration of LeafLet into Next JS 13 for interactive mapping

I'm currently working on integrating a LeafLet map component into my Next JS 13.0.1 project, but I'm facing an issue with the rendering of the map component. Upon the initial loading of the map component, I encountered this error: ReferenceError ...

Guide on inputting Vue component in props

<template> <v-dialog width="auto" v-model="isShown" transition="dialog-bottom-transition" > <v-card> <v-card-title v-if="title"> {{ title }}</v-card-title> ...

Transmitting data from Angular to .NET Core for seamless integration

I have been attempting to send an xls or any other file from my angular application to a .NET core controller, but none of my methods seem to work... Below is my component where I call my service upon button click: handleFileInput(file: FileList) { this. ...

What is the correct way to properly enter a Svelte component instance variable?

Currently, I am delving into learning Svelte and specifically exploring how to bind to a component instance as demonstrated in this tutorial: As I progress through the tutorial, I am attempting to convert it to Typescript. However, I have encountered an ...

Solving automatically generated TypeScript MongoDB types for GraphQL results

Utilizing the typescript-mongodb plugin along with graphql-codegen to automatically generate Typescript types enables easy data retrieval from MongoDB and GraphQL output via Node. The initial input schema in GraphQL format appears as follows: type User @ ...

Transforming a string into key-value pairs using Typescript

Is there a way to transform the given string into key-value pairs? TotalCount:100,PageSize:10,CurrentPage:1,TotalPages:10,HasNext:true,HasPrevious:false ...