Tips for creating a mapped type in TypeScript that is based on an array

Is there a way to create a function with dynamic properties?

function magic(...propertyNames:string[]): { ????? : any }
{
....
}

Could the returned type have properties listed in propertyName?

For instance:

type ResultType = {alpha:any, bravo:any};

let res = magic('alpha', 'bravo'); // res is compatible with ResultType

Answer №1

Below is a potential solution that can trigger some wonders:

declare function magic<T extends string[]>(
  ...propertyNames: T
): Record<T[number], any>;

const result = magic("alpha", "bravo");

type ResultType = typeof result; // {alpha: any; bravo: any;}

Putting the ResultType to test:

const t1: ResultType = {
  alpha: "foo",
  bravo: 42,
  wannaBe: 3 // error (OK)
};

You have the option to further limit the usage of the any type in Record<T[number] any> by adding an extra type parameter, since any doesn't provide much useful typing.

declare function magic<T extends string[], R>(
  ...propertyNames: T
): Record<T[number], R>;

A Little Elaboration

  • T[number] grants us access to all item values as a union type. For example,
type T = ["alpha", "bravo"]
type TItems = T[number] // "alpha" | "bravo"
  • Record ensures that we have all item values "alpha" | "bravo" as property keys.
  • The tuple type can be deduced with the assistance of generic rest parameters.

Playground

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

The parameter type 'Object' cannot be assigned to the parameter type 'string'

Everything seems to be working fine in my application, but I am encountering the following error message: The argument of type 'Object' is causing an issue and cannot be assigned to a parameter of type 'string' Here is the code snip ...

Searching for a string within a JSON object in Angular: step-by-step guide

JSON Data Example { "rootData": { "test1": { "testData0": "Previous information", "testData1": "Earlier Information" }, "test2": { "testData0": ...

Tips on how to retrieve an Observable Array instead of a subscription?

Is there a way to modify this forkJoin function so that it returns an observable array instead of a subscription? connect(): Observable<any[]> { this.userId = this.authService.userId; this.habits$ = this.habitService.fetchAllById(this.userId); this.s ...

Is there a way to assign a value to an Angular-specific variable using PHP?

In the development of my Angular 4 application, I encountered an issue while receiving JSON data based on an id value through a PHP script. Upon examining the code, it seems that there should be a value passed into this.PropertiesList. examineProperties(i ...

How to Send Data with NodeJS by Utilizing the Finish Event

Is there a way to retrieve the JSON data sent during the nodejs finish event? This is how I send the JSON data: oResponse.json({ version: "1.0.0", author: "Someone", contributors: "also Someone" }); I would like ...

"Receiving an error message stating 'Was expecting 1 parameter, received 2' while trying to pass a useState function in TypeScript

I am encountering an issue with a component where I pass a useState setter to a utility function: export interface IData { editable: string[]; favourited: string[]; } const [data, setData] = useState<IData | undefined>(undefined) useEffect(() = ...

I encountered an issue with Cypress when attempting to utilize a custom command. The error message "TypeError cy.login is not a function" keeps popping up. Any suggestions on how to resolve this

I am currently working on a TypeScript project and I am attempting to write some tests using Cypress. However, I encountered the following error: TypeError - cy.login is not a function. This error occurred during a before each hook, so we are skipping the ...

Looking for a SSR Component to Choose Dates?

In the process of designing a landing page, I encountered a challenge with incorporating a date picker feature. My goal is to have users select a date and then be redirected to another page upon clicking a button. The technology stack includes NextJS where ...

Typescript: The property 'userId' is not found within the 'unknown' type

For my rxJS practice in Typescript, I wrote the following simple code. import fetch from 'node-fetch'; import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent, SubscriptionLike, PartialObserver } from &apo ...

The enum cannot be assigned a type of 'string | null'

Within my ProductGender enum, I have: enum ProductGender { Men, Women, } In my getProducts service: public getProducts( gender: ProductGender, category: ProductCategory ): Observable<IProductInterface[]> { return this.httpPro ...

Angular8: Adjusting Activity Status After Leaving Page

When performing activities like upload, download, delete, and edit, I display statuses such as 'upload started' or 'upload completed'. This works perfectly when staying on the same page. However, there are instances where a user may nav ...

Create an interface that adheres to the defined mapped type

Working on a typescript project, I have defined the mapped type GlanceOsComparatorV2 interface DonutData { label: string; value: number; } interface ProjectMetric { value: number; } enum ZoneMetricId { ClickRate = 'clickRate', } enum Pa ...

Issues with loading Angular 9 application on Internet Explorer 11

Having trouble with my app not loading in IE 11 after adding ngx-treeview. Encountering the error (SCRIPT1002: Syntax error), Script Error Error point in vendor.js Unsure how to resolve this issue. Works fine in chrome and firefox, but in IE11 all I se ...

Is "await" considered as a reserved word in ReactJS when using TypeScript?

I am trying to implement async await in my code, but I keep getting an error that says await is a reserved word. Here is the snippet of my code: public componentDidMount() { this.startDrag(); } private startDrag = async () => { const eleme ...

Ionic 3: Struggling to Access Promise Value Outside Function

I've encountered an issue where I am unable to retrieve the value of a promise outside of my function. It keeps returning undefined. Here's what I have attempted so far: Home.ts class Home{ dd:any; constructor(public dbHelpr:DbHelperProvider ...

Errors are not displayed in vee-validate for objects

When utilizing [email protected] [email protected] the problem arises while attempting to validate a nested object and displaying an error. An example was created based on the documentation. However, when trying to include :has-error="Bo ...

What steps can be taken to resolve the issue of being unable to rename an element in Typescript?

Why does VS code editor sometimes prevent me from renaming my typescript symbol using the f2 key? I keep encountering the error message "This element cannot be renamed." https://i.stack.imgur.com/mmqu9.png In some of my other projects, I am able to renam ...

The process of prioritizing specific elements at the top of an array when ordering

In my array, I want to prioritize specific items to always appear at the top. The API response looks like this: const itemInventorylocationTypes = [ { itemInventorylocationId: '00d3898b-c6f8-43eb-9470-70a11cecbbd7', itemInvent ...

Learn how to capture complete stack traces for errors when using Google Cloud Functions

In the codebase I am currently working on, I came across a backend service that I would like to utilize for logging all errors along with their corresponding Http statuses. If possible, I also want to retrieve the full stack trace of these errors from this ...

A step-by-step guide on incorporating MarkerClusterer into a google-map-react component

I am looking to integrate MarkerClusterer into my Google Map using a library or component. Here is a snippet of my current code. Can anyone provide guidance on how I can achieve this with the google-map-react library? Thank you. const handleApiLoaded = ({ ...