Linking key value pairs through a TypeScript interface

coding

  interface StoreActions {
    setUserName: string
    actionOne: string[]
    actionTwo: { testValue: string }
  }

  interface CustomActions extends AnyAction {
    typeOfAction: keyof StoreActions
    // additionalData:???
  }

The attribute typeOfAction in CustomActions corresponds to the keys in StoreActions

Anticipated Results

  • For typeOfAction = 'setUserName', the data type is string
  • For typeOfAction = 'actionOne', the data type is string[]
  • For typeOfAction = 'actionTwo', the data type is { testValue: string }

Feasibility and Method

Answer №1

If you're faced with this scenario, there are a couple of routes you can take.

  1. One approach is to utilize a discriminated union encompassing all possible types. By creating the union using a mapped type, TypeScript can effectively narrow down the type. This method is generally recommended for its efficiency. Check out this Playground to see it in action.

    interface StoreActions {
        setUser: string
        action1: string[]
        action2: { test: string }
    }
    
    type MakeUnion<T> = {
        [K in keyof T]: { type: K, data: T[K] }
    }[keyof T]
    
    
    interface AnyAction {
        other: 'common properties that all actionsH members have'
    }
    
    type ActionsH = MakeUnion<StoreActions> & AnyAction
    
  2. Alternatively, you can make the interface generic and use the key from the generic to determine the type of the data property. This method allows for greater flexibility and customization. Visit this Playground to experiment with this concept.

    interface StoreActions {
        setUser: string
        action1: string[]
        action2: { test: string }
    }
    
    interface AnyAction {
        other: 'common properties that all actionsH members have'
    }
    
    interface ActionH<K extends keyof StoreActions> extends AnyAction {
        type: K
        data: StoreActions[K]
    }
    

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

When using TypeScript, a typed interface will not permit a value that is not within its specified string literal type

I have downsized my issue to a smaller scale. This class needs to set the default value of its "status" property. The type T extends the string literal type "PossibleStatus" which consists of 3 possible strings. Typescript is giving me trouble with this. ...

I'm encountering issues with undefined parameters in my component while using generateStaticParams in Next.js 13. What is the correct way to pass them

Hey there, I'm currently utilizing the App router from nextjs 13 along with typescript. My aim is to create dynamic pages and generate their paths using generateStaticParams(). While the generateStaticParams() function appears to be functioning corre ...

Can all objects within an interface be iterated through in order to retrieve both the key and its corresponding value?

I have created an interface that is capable of accepting a variety of search criteria and then passing it to a service that will incorporate those values into the service URL. I am wondering if there is a way to iterate through all the objects in the inter ...

When you use array[index] in a Reduce function, the error message "Property 'value' is not defined in type 'A| B| C|D'" might be displayed

Recently, I delved deep into TypeScript and faced a challenge while utilizing Promise.allSettled. My objective is to concurrently fetch multiple weather data components (such as hourly forecast, daily forecast, air pollution, UV index, and current weather ...

Is the "Angular is not functioning" error message the result of a missing import?

Encountering an 'is not a function' error in Angular 7 / TypeScript 3, using an EventEmitter. This issue has been extensively discussed (a b), but solutions have not garnered many upvotes (a b c d e f). I am close to resolving it, but need s ...

Receiving feedback from an http.post request and transferring it to the component.ts file in an Angular

Currently, I am facing an issue with passing the response from an http.post call in my TypeScript service component to an Angular 2 component for display on the frontend. Below are the code structures of my service.ts and component.ts: getSearchProfileRes ...

Angular, perplexed by the output displayed in the console

I'm completely new to Angular and feeling a bit lost when it comes to the console output of an Angular app. Let me show you what I've been working on so far! app.component.ts import { Component } from '@angular/core'; @Component({ ...

Discover the power of TypeScript's dynamic type inference in functions

Below is a function that selects a random item from an array: const randomFromArray = (array: unknown[]) => { return array[randomNumberFromRange(0, array.length - 1)]; }; My query pertains to dynamically typing this input instead of resorting to u ...

The status of the 'slider' may be 'undefined'

I'm really struggling to figure out how to resolve this issue, even though I suspect it's a simple fix that's eluding me... Here is the part of my code in TypeScript that's causing the error: const slideLeft = () => { cons ...

Developing middleware for managing event handlers

Scenario: I am tasked with managing multiple events that necessitate an "available client". Therefore, in each event handler, my first step is to attempt to acquire an available client. If no client is available, I will send a "Service unavailable" messag ...

Addressing ESLint and TypeScript Issues in Vue.js with Pinia: A comprehensive guide

Experiencing difficulties with Vue.js + Pinia and need assistance to resolve these issues. Error: 'state:' is defined but never used. Here is the snippet of code located in @/stores/user.ts. import { defineStore } from 'pinia' export ...

Cosmic - Ways to incorporate personalized validation strategies into the `getConfigValue()` function?

Why is the getConfigValue() function not retrieving validation values from custom Strategies? For example: @Injectable() export class CustomStrategy extends NbPasswordAuthStrategy { protected defaultOptions: CustomStrategyOptions = CustomStrategyOptio ...

Bring in a function by its name from the ts-nameof package that is not declared in the d.ts export

Recently, I came across a captivating package that caught my interest and I would love to incorporate it into my TypeScript application: https://github.com/dsherret/ts-nameof However, upon attempting to import the nameof function, I realized it was not be ...

What is the best way to swap out the if else statement with a Ternary operator within a JavaScript function?

Is there a way to replace the if else statement in the function using a Ternary operator in JavaScript? private getProductName(productType: string): string { let productName = 'Product not found'; this.deal.packages.find(p => p.isSele ...

Exporting Types in an NPM Package: Best Practices

Struggling to create a private NPM package for internal use within my company's Nodejs applications using Typescript. Currently, I have a basic proof of concept with some constants, but I'm having trouble structuring it in a way that is importabl ...

Next.js is having trouble identifying the module '@types/react'

Every time I attempt to launch my Next.js app using npm run dev, an error notification pops up indicating that the necessary packages for running Next with Typescript are missing: To resolve this issue, kindly install @types/react by executing: np ...

Using references to pass variables in TypeScript [Angular 8]

I have several variables within the html of this component that are assigned their values by the typescript file. The declaration in the html is as follows: <h1>{{myproperty1}}<\h1> <h1>{{myproperty2}}<\h1> <h1>{{myp ...

Develop a custom class for importing pipes in Angular 4

Currently, I am working on creating a pipe that will replace specific keywords with the correct strings. To keep this pipe well-structured, I have decided to store my keywords and strings in another file. Below is the code snippet for reference: import { ...

Creating a dynamic union type in Typescript based on the same interface properties

Is it possible to create a union type from siblings of the same interface? For example: interface Foo { values: string[]; defaultValue: string; } function fooo({values, defaultValue}: Foo) {} fooo({values: ['a', 'b'], defaultVal ...

Asynchronously download static images with the power of NextJS and TypeScript integration

I have a query regarding my website development using NextJS and TypeScript. The site features a showcase gallery and is completely static. Currently, the initial view shows thumbnails of images. When clicking on a thumbnail, the original image is display ...