Create a function that takes in an array of strings and outputs a record containing a unique key for each string in the array

Looking to create a function that takes an array of strings as input and returns an object with a key for each string in the input array?

Here is an example of how this can be implemented:

const getMyObject = (...keys: string[]) => keys.reduce((object, key) => ({
    ...object,
    [key]: `some-computed-value-${key}`,
  }), 
  {},
)

This allows you to safely write code like this:

const { keyA, keyB } = getMyObject('keyA', 'keyB');

If you're unsure about properly typing this function, we can explore different options.

Answer №1

If you're looking for a solution, you might consider using the following code snippet:

const getMyObject = <K extends string>(
  ...keys: K[]
// Record<K, TypeOfTheComputedValues>
): Record<K, string> => keys.reduce((obj, key) => ({
    ...obj,
    [key]: `some-computed-value-${key}`,
  }), 
  {},
) as Record<K, string>;

It's worth noting that a type assertion is still necessary due to the type of the accumulator in reduce only being recognized as Record<K, string> during the last iteration, which TypeScript may not automatically infer.

Playground link

Answer №2

One can deduce values as well:

type Predicate<T> = T extends string ? Record<T, `some-calculated-value-${T}`> : never

type Reducer<
  Arr extends Array<unknown>,
  Result extends Record<PropertyKey, unknown> = {}
  > = Arr extends []
  ? []
  : Arr extends [infer H]
  ? Result & Predicate<H>
  : Arr extends [infer Head, ...infer Tail]
  ? Reducer<[...Tail], Result & Predicate<Head>>
  : Readonly<Result>;

const fetchMyObject = <K extends string, Keys extends K[]>(...keys: [...Keys]) =>
  keys.reduce((obj, key) => ({
    ...obj,
    [key]: `some-calculated-value-${key}`,
  }),
    {} as Reducer<Keys>,
  )

const { keyA, keyB } = fetchMyObject('keyA', 'keyB'); // keys and values inferred
const { keyC, keyD } = fetchMyObject('keyA', 'keyB'); // Errors, properties do not match

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

Alter the language settings of the Datepicker feature in Material Angular 4

Need help changing the language of Datepicker in Material Angular. Struggling to locate this information in the Angular material 2 documentation. Check out this plunkr https://plnkr.co/edit/unzlijtsHf3CPW4oL7bl?p=preview <md-input-container> < ...

When the page is refreshed, Vercel's Next.JS success/error pattern is thrown due to the "window is not defined" error

Currently, I am working on enhancing a Next.js website that is hosted on Vercel. Upon deploying the page, I encountered the following error initially: GET] / 17:53:00:19 2022-09-12T14:53:00.262Z 938c1a2e-ce7c-4f31-8ad6-2177814cb023 ERROR Uncau ...

Utilizing npm/buffer package within a TypeScript module

I'm interested in implementing this NPM package: https://www.npmjs.com/package/buffer I'm unsure about how to convert this line of code into typescript: var Buffer = require('buffer/').Buffer Could you provide me with the correct code ...

Constructor not executing when using Object.create

Attempting to instantiate a class within a static method, I am using Object.create(this.prototype), which appears to be functioning correctly. Nonetheless, when I check the console, my property items is showing as undefined. The base class called model lo ...

Troubleshooting a Gulp.js issue during the execution of a "compile" task

Currently, I am utilizing gulp to streamline a typescript build system specifically designed for an Angular 2 frontend. However, I have encountered a problem with my "build" task that has been configured. Below is the exact task in question: gulp.task(&a ...

Jest is having trouble recognizing a custom global function during testing, even though it functions properly outside of testing

In my Express app, I have a custom function called foo that is globally scoped. However, when running Jest test scripts, the function is being recognized as undefined, causing any tests that rely on it to fail. This is declared in index.d.ts: declare glob ...

Is there a way to position the label to the left side of the gauge?

Is there a way to position the zero number outside the gauge? I'm having trouble figuring out how to do it because the x & y options won't work since the plotLine's position keeps changing. The zero needs to move along with the plotLine and ...

Leveraging Expose in combination with class-transformer

I have a simple objective in mind: I need to convert the name of one property on my response DTO. refund-order.response.dto.ts export class RefundOrderResponseDto { @Expose({ name: 'order_reference' }) orderReference: string; } What I w ...

Steer clear of type assertion in your codebase when utilizing useSelector alongside Redux, Immutable.js, and TypeScript

Currently, I am working with a combination of Redux, Immutable.js, and TypeScript. I am facing challenges in obtaining proper types from the useSelector hook, which is leading me to use type assertions. I acknowledge that this is not the best practice and ...

Enhance the performance of your React/NextJS app by controlling the rendering of a component and focusing on updating

I'm facing an issue with my NextJS application that showcases a list of audio tracks using an <AudioTrackEntry> component. This component receives props like the Track Title and a Link to the audio file from an external data source. Within the ...

Angular 2 Guide on macOS Sierra Shows "Page Not Found" Error in Web Browser

I've been delving into Angular 2 with TypeScript on my OS X machine. Following the tutorial to the T, I didn't encounter any errors during compilation. Upon executing the npm start command, everything seemed to be smooth sailing as a new tab open ...

Transferring data between components in Ionic 2: Service to Page

My service code includes two functions - one for creating a native storage with IP and port, and the other for retrieving values from the native storage. DatabaseService export class DatabaseService { ... public ip: string; public port: string; . ...

Experience the power of combining React with typescript, webpack, and ui-router-react for

After carefully studying the ui-router-react documentation (), I am encountering several challenges with webpack compilation when importing import {UIRouter, UIView, UISref, UISrefActive, pushStateLocationPlugin} from 'ui-router-react'; This is ...

Accessing a targeted XML file within a document using Office.js in a Word Add-In

I am struggling to load the file named item1.xml from the ..\customXml folder of my document into my Word Add-In. So far, I have attempted the following: var url = Office.context.document.url + '\\customXml\\item1.xml\& ...

Angular can tailor its view templates to suit either mobile or desktop platforms

I'm currently developing an application that requires displaying different views depending on whether the site is accessed from a desktop or mobile device. While I already have a responsive design in place, I want to incorporate ionic components for a ...

Properly incorporating a git+https dependency

I'm facing an issue while trying to utilize a git+https dependency from Github to create a TypeScript library. I've minimized it to a single file for illustration purposes, but it still doesn't work. Interestingly, using a file dependency fu ...

The altered closure variable ts remains undetectable

Check out the live demonstration I made changes to the flag variable, but TypeScript did not recognize it. Could this be a coding issue? function fn () { let flag = true function f () { // alter the value of flag flag = false } for (let ...

Tips on displaying a spinner only when data is retrieved from an Http service

How can I ensure that a spinner is only shown during an HTTP service call and dismissed when my component receives data? To address this issue, I implemented a cache service to store data fetched from the HTTP service for future use. However, I want to sh ...

express-validator not providing any feedback from endpoint when integrated with TypeScript

I've been working on validating the response body for my endpoint, but I'm running into an issue where I'm not getting a response from that endpoint when using express-validator. I'm confident that I have followed the official documenta ...

You cannot directly access an array useState by index in React js, but you can use the map function to

export interface JobListing { id: number, isTraded: boolean, feedback: string, title: string, message: string, skills: string[], sender: string, ipAddress: string } const GroupList = () => { const [jobListings, setJobListings] = useSt ...