Generate a blueprint for a TypeScript interface

In my coding project, I've been noticing a pattern of redundancy when it comes to creating TypeScript interfaces as the code base expands.

For example:

interface IErrorResponse {
  code: number
  message: string
}

// Feature 1
type FEATURE_1_KEYS =
  | 'fetchingActivities'
  | 'fetchingActivityTypes'

interface IFeature1ErrorAction
  extends IErrorResponse {
  key: FEATURE_1_KEYS
}

// Feature 2
type FEATURE_2_KEYS =
  | 'fetchingSomethingElse'
  | 'updatingSomething'

interface IFeature2ErrorAction
  extends IErrorResponse {
  key: FEATURE_2_KEYS
}

Currently, I find myself using IFeature1ErrorAction and IFeature2ErrorAction for the final error actions in my project which consists of multiple features.

Is there a way to streamline this process by creating an IErrorAction that builds from IErrorResponse, allowing me to simply pass in the respective FEATURE_KEYS for the key?

This would enable me to use

IErrorAction<FEATURE_1_KEYS>
like so.

This optimization would greatly reduce repetition during development, although I'm unsure about the exact implementation at this stage.

The desired outcome for the interface

IErrorAction<FEATURE_1_KEYS>
would be as follows:

interface IErrorAction = { // How can I incorporate that `TEMPLATED_KEYS`?
  code: number,
  key: TEMPLATED_KEYS,
  message: string
}

Answer №1

To create a more flexible base interface, you can make it generic by allowing a type parameter that is a subtype of string:

interface IErrorResponse<TFeatures extends string> {
  code: number
  message: string
  key: TFeatures
}

// Defining keys for Feature 1
type FEATURE_1_KEYS =
  | 'fetchingActivities'
  | 'fetchingActivityTypes'

type IFeature1ErrorAction = IErrorResponse<FEATURE_1_KEYS> // 

// Defining keys for Feature 2
type FEATURE_2_KEYS =
  | 'fetchingSomethingElse'
  | 'updatingSomething'

type IFeature2ErrorAction = IErrorResponse<FEATURE_2_KEYS>

You have the option to alias

IErrorResponse<FEATURE_1_KEYS>
and
IErrorResponse<FEATURE_2_KEYS>
as shown above or use them directly in your code.

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

On the subsequent iteration of the function, transfer a variable from the end of the function to the beginning within the same

Can a variable that is set at the end of a function be sent back to the same function in order to be used at the beginning of the next run? Function function1 { If(val1.id == 5){ Console.log(val1.id val1.name) } else{} Val1.id = 5 Val1.name = 'nam ...

Is it possible in C++ to assign a single type to multiple templates at the same time?

The concept behind this discussion is rooted in the sample code provided below, which draws inspiration from Sean Parent's talk. The purpose of the code snippet presented is to create an object wrapper akin to boost::any. I crafted this code as a mean ...

Typescript throws an error when attempting to return an array of strings or undefined from a function

I created a shallow differences function that compares two arrays of strings and returns either undefined (if the arrays are different lengths) or a string array containing matching characters at corresponding indexes. If the characters don't match, i ...

Issue encountered while accessing theme properties in a ReactJs component with Typescript

I am trying to pass the color of a theme to a component in my TypeScript project (as a beginner). However, I have encountered an error that I am struggling to resolve. The specific error message reads: 'Parameter 'props' implicitly has an ...

The detection of my query parameters is not working as expected

Creating an Angular application that dynamically loads a different login page based on the "groupId" set in the URL is my current challenge. The approach involves sending each client a unique URL containing a specific "groupId" parameter. A template is the ...

React fails to acknowledge union types

I have the following types defined: export enum LayersItemOptionsEnum { OPERATOR, HEADER, } type sharedTypes = { children: string | ReactElement; }; type LayersItemStatic = sharedTypes & { label: string; option: LayersItemOptionsEnum; }; t ...

Having difficulty invoking the forEach function on an Array in TypeScript

I'm currently working with a class that contains an array of objects. export interface Filter { sf?: Array<{ key: string, value: string }>; } In my attempt to loop through and print out the value of each object inside the array using the forE ...

Why is it that when I try to create a table using the "Create Table" statement, I keep getting an error saying "Near '(': syntax error"?

Error : There seems to be a syntax error near "(". Here is the SQL statement causing the issue: CREATE TABLE IF NOT EXISTS tickets ( numero INTEGER PRIMARY KEY AUTOINCREMENT, identifier VARCHAR(4) NOT NULL, subject VARCHAR(150) NOT NULL, ...

Can we establish the set values for a function's parameter in advance?

I need to define the available values for a function's parameter in this way: let valueList = [ 'val1', 'val2', 'val3', ]; let getSomething = (parameter: valueList) => { // do something } I want the con ...

Utilizing asynchronous operations dependent on the status of a separate entity

Dealing with asynchronous operations in Vue has been a challenge for me. Coming from a C# background, I find the async-await pattern more intuitive than in JavaScript or TypeScript, especially when working with Vue. I have two components set up without us ...

Having difficulty transferring types to and from a custom module?

I'm currently faced with an issue while working on a typescript module within a larger monorepo. I am having difficulty importing types from one package into another via node modules. The types are located at ./types, and my package.json contains a ke ...

Modifying Data with MomentJS when Saving to Different Variable

After attempting to assign a moment to a new variable, I noticed that the value changes on its own without any modification from my end. Despite various attempts such as forcing the use of UTC and adjusting timezones, the value continues to change unexpec ...

Problems with importing modules in Apollo Server

I've encountered a never-ending stream of error messages post importing Apollo Server into my Typescript-based Node.js application. (Check out the screenshot below) It appears that Apollo is unable to locate anything in the graphql dependency. Could ...

Import Information into Popup Window

When a user clicks on the "view" button, only the details of the corresponding challenge should be displayed: Currently, clicking on the "view" button loads all the challenges. This is because in my view-one-challenge.component.html, I have coded it as fo ...

Issue with Angular 2 pipe causing unexpected undefined result

Here is a JSON format that I am working with: [{ "id": 9156, "slug": "chicken-seekh-wrap", "type": "dish", "title": "Chicken Seekh Wrap", "cuisine_type": [2140] }, { "id": 9150, "slug": "green-salad", "type": "dish", "title": "Green Sala ...

Navigate to a new page by utilizing the nav.push function while incorporating a side menu in your

Trying to develop a small application using ionic2 to enhance my understanding of it, however, facing some challenges with navigation. I've grasped the distinction between a rootpage (adjusted with nav.setRoot) and a regular page (added through nav.p ...

What is preventing me from generating Face3 in my ThreeJS Typescript project

Currently, I'm in the process of generating a Mesh using Face3 within a TypeScript project that utilizes Three.js. However, I've encountered a few issues along the way. const points = [ new Face3(-1, 1, -1),//c new Face3(-1, -1, 1),//b ...

Unable to grab hold of specific child element within parent DOM element

Important Note: Due to the complexity of the issue, the code has been abstracted for better readability Consider a parent component structure like this: <child-component></child-component> <button (click)="doSomeClick()"> Do Some Click ...

Testing MatDialog functions in Angular: Learning how to open and close dialogues

I am currently facing an issue with testing the MatDialog open and close functions. No matter what I try, I cannot seem to successfully test either the open or close functions. I am wondering how I can mock these functions in order to properly test them. W ...

Ensuring the selected date matches any consecutive dates within the dates array in Angular

Imagine if 01/01/2022 is chosen from the input field, and my array of dates looks something like this: ['31/12/2021', '01/11/2021', '02/01/2022'...] In this scenario, when '31/12/2021' and '02/01/2022' are ...