Defining types for an object with identical keys and values

Is there a way in TypeScript to define the types for a function that takes a list of strings and returns an object where each key's value is the key itself?

const createActionTypes = (types: string[]) => {
  return types.reduce((typesMap, type) => {
    typesMap[type] = type
    return typesMap
  }, {})
}
// Input
createActionTypes(['a', 'b'])

// Output
{ a: 'a', b: 'b' }

I've attempted the following approach but without success:

const createActionTypes = <T extends readonly string[], U extends T[number]>(
  types: T
): { [key in U]: U } => {
  return types.reduce((typesMap, type) => {
    typesMap[type] = type
    return typesMap
  }, {})
}

const x = createActionTypes(['a', 'b'] as const)
// The typings for x resolve to: 
{
  a: "a" | "b";
  b: "a" | "b";
}

Answer №1

You're really close to the solution. Just remember to specify that the value should be of the same type as the key, not the entire set like "a"|"b", which is represented by U.

For more details, check out this link: TS Playground Link

const createActionTypes = <T extends readonly string[], U extends T[number]>(
  types: T
): { [key in U]: key } => {
  return types.reduce((typesMap, type) => {
    typesMap[type] = type
    return typesMap
  }, {} as any)
}

const x = createActionTypes(['a', 'b'] as const)

Also, for better clarity, it's advisable to avoid using reserved words like type as a variable or function parameter. This way, it's easier for others to understand your code at first glance.

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

Error: The absence of an element identified by the locator does not cause the protractor spec to fail, but rather it executes successfully

This automation framework follows the page object model and utilizes the async/await approach rather than promises. TypeScript is used, with compilation to JavaScript (protractor) for script execution. Page Object: async addProjectDetails(): Promise< ...

Tips for clearing out text in a <p> tag with javascript when it exceeds a specific length of 100 characters

Is there a way to automatically truncate text to (...) when it exceeds 100 characters inside a paragraph with the class .class? For instance, if I have a long paragraph like this: <div class='classname'> <p>Lorem ipsum dolor sit ame ...

A pronounced distinction exists between ionInput and ionChange functionality

Q. Can you explain the difference between (ionInput) and (ionChange) events in Ionic framework? When would it be more appropriate to use one over the other? I have experimented with both event handlers below and found that they produce the same expected r ...

A guide to successfully transferring data array values from a Parent Component to a Child Component using APIs in Angular

To transfer values of this.bookingInfo = bookings.responseObj.txnValues; array from the parent component to the bookingInfo array in my child component and then insert that data into the chartNameChartTTV.data = []; array in the child component. Here, divN ...

What is the correct way to initialize and assign an observable in Angular using AngularFire2?

Currently utilizing Angular 6 along with Rxjs 6. A certain piece of code continuously throws undefined at the ListFormsComponent, until it finally displays the data once the Observable is assigned by calling the getForms() method. The execution of getForm ...

Experiencing TypeScript error in VSCode while trying to run in Nodejs? Here's how to troubleshoot and resolve

Experimenting with the performance measurement code provided by Nodejs in VSCode has been an interesting challenge for me. I encountered no issues running the code in Nodejs, and it executed smoothly. However, when attempting to run the code in VSCode, er ...

Exploring the relationships between nested tuple types

When exploring the concept of mapped tuple types in TypeScript, the documentation provides an example: type MapToPromise<T> = { [K in keyof T]: Promise<T[K]> }; type Coordinate = [number, number] type PromiseCoordinate = MapToPromise<Coor ...

Waiting patiently for the arrival of information, the dynamic duo of Angular and Firebase stand poised and

Here is the given code snippet: signIn(email, password) { let result = true; firebase.auth().signInWithEmailAndPassword(email, password).catch(error => result = false); waits(100); return result; } I have a ...

Is it possible to create a reusable TypeScript interface for an array of functions?

Currently working with Vue and Typescript, I'm exploring different ways to describe types for an array of functions. In my current code, I have the following setup. Is there a way I could define an interface called formRules instead of repeatedly decl ...

Ways to mimic an Angular subscription during a Jasmine test

I'm currently troubleshooting a unit test for my code (I'm not very experienced with Jasmine) after adding some subscriptions to a service. I'm encountering an issue where the subscriptions are coming up as undefined. I'm not entirely s ...

Unsure about Typescript object structures {} and []?

I am new to using lists and object lists in Typescript and I'm unsure of how they function. In the code snippet below, a few objects are created and some temporary values are assigned to them through a loop. However, my goal is to have the console log ...

How to Retrieve Observable<Record<string, boolean>> Value with the Help of AsyncPipe

My service retrieves permissions for the currently logged-in user as a record. The necessary observable is declared in my TypeScript file as a member variable: permissionsRecord$: Observable<Record<string, boolean>>; When I call the service, ...

Having trouble with npm i after installing the newest versions of node and npm

I recently upgraded my node and npm to the latest versions. However, my ionic 3 project (version 3.9.2) is now encountering issues when I run npm i. Strangely, this problem only occurs with this specific project and not with new projects. Any help in resol ...

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...

How to compare and filter items from two arrays using TypeScript

I am looking to filter out certain elements from an array in TypeScript Original Array: [ {"Id":"3","DisplayName":"Fax"}, {"Id":"1","DisplayName":"Home"}, {"Id":&quo ...

Typescript tutorial: Implementing a 'lambda function call' for external method

The Issue Just recently diving into Typescript, I discovered that lambda functions are utilized to adjust the value of this. However, I find myself stuck on how to pass my view model's this into a function that calls another method that hasn't b ...

Retrieve the implementation of an interface method directly from the constructor of the class that implements it

I am looking to create a function that takes a string and another function as arguments and returns a string: interface Foo { ConditionalColor(color: string, condition: (arg: any) => boolean): string; } I attempted to pass the ConditionalColor metho ...

Typegoose and NestJS: The 'save' property is not found on this type

I recently started using typegoose and nestjs for my backend-server. In my pages.service.ts file, I already have a function called getPageById() to retrieve a single page by its ID. However, when trying to call this function from another function within th ...

Creating a Text Typer ReactJS component that functions properly regardless of whether or not it is used within StrictMode is no

My goal is to develop a custom Text Typer component that displays text character by character every 100ms. While it works perfectly fine in production, I encounter issues when testing it in the development environment. Despite trying various solutions, tw ...

Vue is having trouble identifying the src attribute

I recently finished a project utilizing @vue/[email protected] (Babel, TypeScript, Router, Vuex, CSS Pre-processors, Linter/formatter) After running the command npm run serve I encountered the following error message: These dependencies were not ...