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

Guide on showing the content of an uploaded file as an object in JavaScript using file reader

When using the file upload function to upload a json file and read its contents, I am encountering an issue where the result is in string format instead of object. How can I display it as an object? Here is my code: .html <div class="form-group"> ...

Prisma and Next.js: Changes to content require re-deployment for updates to take effect

Just recently, I launched a new website on Vercel. My web application is being built with Prisma and Next.js. However, I'm currently facing an issue where the content doesn't update in real-time unless I manually re-deploy the application. Here&a ...

Tips for simulating difficult private attributes within a class during unit testing in TypeScript

Is there a way to mock the value of a hard private property in a unit test? For example, how can I expect something like expect(event.getEventHis()).toBeEqual(['a', 'b']) export class EventController { #event: []; constructor() { ...

Errors in Visual Studio regarding typescript are often not found by tsc and eslint, causing frustration for developers

Today, after restarting my computer and launching visual studio code, I encountered an unfamiliar error that I've never seen before: I haven't made any changes to my project's code (confirmed by running git status). It's unclear whethe ...

Typescript loading icon directive

Seeking to create an AngularJS directive in TypeScript that wraps each $http get request with a boolean parameter "isShow" to monitor the request status and dynamically show/hide the HTML element depending on it (without utilizing $scope or $watch). Any ...

react-hook-form replaces the onChange function causing delays in updating the value

Recently, I created a unique Select component utilizing useState and onChange. I attempted to integrate this custom component with the powerful react-hook-form. Allow me to share the code snippet for the bespoke Select component. const Select = forwardRef ...

Is there a way to turn off eslint's no-promise-executor-return rule?

Can the eslint rule 'no-promise-executor-return' be disabled? my .eslintrc file { "env": { "es6": true, "node": true }, "extends": [ "airbnb-base" ], "globals": { "de ...

Retrieve both the name and id as values in an angular select dropdown

<select (change)="select($event.target.value)" [ngModel]="gen" class="border border-gray-200 bg-white h-10 pl-6 pr-40 rounded-lg text-sm focus:outline-none appearance-none block cursor-pointer" id="gend ...

Is it possible to create a map of functions that preserves parameter types? How can variadic tuple types in TypeScript v4 potentially enhance this

Initially, I faced a challenge when trying to implement a function similar to mapDispatchToProps in Redux. I struggled with handling an array of functions (action creators) as arguments, but managed to come up with a workaround that works, although it feel ...

A guide on leveraging Jest and Typescript to mock a static field within a class

While working with Typescript and a third-party library, I encountered an issue trying to write unit tests that mock out the library. Here's an example scenario: // Library.ts // Simulating a third party library export class Library { static code ...

Error: The AppModule is missing a provider for the Function in the RouterModule, causing a NullInjectorError

https://i.stack.imgur.com/uKKKp.png Lately, I delved into the world of Angular and encountered a perplexing issue in my initial project. The problem arises when I attempt to run the application using ng serve.https://i.stack.imgur.com/H0hEL.png ...

Encountering a surprise token < while processing JSON with ASP.NET MVC alongside Angular

I encountered an issue when attempting to return the Index page. The data is successfully sent from the client to the server, but upon trying to display the Index page, an error occurs. Could someone review my code and identify where the mistake lies? acc ...

In TypeScript, the 'as const' syntax results in a syntax error due to the missing semicolon

I incorporated the following code into my react project: export const animation = { WAVES: "waves", PULSE: "pulse", } as const; export type Animation = typeof animation[keyof typeof animation]; Upon running the project, I encounte ...

What is the best way to broaden the capabilities of function objects through the use of

Below is a code snippet that raises the question of how one should define certain types. In this scenario, it is required that Bar extends Foo and the return type of FooBar should be 'a'. interface Foo { (...args: any):any b: string } i ...

What is the method to invoke a function within another function in Angular 9?

Illustration ` function1(){ ------- main function execution function2(){ ------child function execution } } ` I must invoke function2 in TypeScript ...

Observable<void> fails to trigger the subscriber

I am currently facing a challenge with implementing a unit test for an Observable in order to signal the completion of a process. While there is no asynchronous code in the logout function yet, I plan to include it once the full logic is implemented. The m ...

GraphQL query result does not contain the specified property

Utilizing a GraphQL query in my React component to fetch data looks like this: const { data, error, loading } = useGetEmployeeQuery({ variables: { id: "a34c0d11-f51d-4a9b-ac7fd-bfb7cbffa" } }); When attempting to destructure the data, an error ...

Sort and incorporate elements by multiple strings present in an array

Looking to filter and include strings in an array by matching them with items in another array? Here is a sample code snippet that filters based on a single string: const filteredString = `${this.filter}`.toLowerCase(); this.filteredCampaigns = this. ...

Tips for effectively utilizing a Query or QueryTask with local graphics (GraphicsLayer)

Working on developing an ESRI map prototype using Angular4, I have successfully utilized the Draw tool to initiate a Query on a FeatureLayer to draw various graphics such as ConvexHull and Buffer. The primary goal was to create a clear Buffer graphic over ...

How to showcase the data retrieved via BehaviorSubject in Angular

I've been working on retrieving data from an API using a service and passing it to components using BehaviorSubject in order to display it on the screen: Here is the service code snippet: @Injectable({ providedIn: 'root', }) export clas ...