What is the best way to allocate string types from an enum using Typescript?

Within my code, I have an enum that includes a collection of strings

export enum apiErrors {
    INVALID_SHAPE = "INVALID_SHAPE",
    NOT_FOUND = "NOT_FOUND",
    EXISTS = "EXISTS",
    INVALID_AUTH = "INVALID_AUTH",
    INTERNAL_SERVER_ERROR = "INTERNAL_SERVER_ERROR"
}

I have created an interface as follows:

export interface IApiResponse {
    status: boolean;
    payload: any;
    errorCode?: string; // I would like this to only accept values like "INVALID_SHAPE" or "NOT_FOUND" and so forth...
}

I am aware that I could simply use "INVALID_SHAPE" | "NOT_FOUND"

Is there a method to destructure the enum for errorCode in order to restrict it to accept only those specific strings?

Answer №1

When setting the errorCode to the apiErrors enum, as pointed out by @JBNizet and @AviadP, Typescript ensures that any implementation of the IApiResponse interface must have the errorCode assigned one of those predefined values.

export enum apiErrors {
   INVALID_SHAPE = "INVALID_SHAPE",
   NOT_FOUND = "NOT_FOUND",
   EXISTS = "EXISTS",
   INVALID_AUTH = "INVALID_AUTH",
   INTERNAL_SERVER_ERROR = "INTERNAL_SERVER_ERROR"
}

export interface IApiResponse {
   status: boolean;
   payload: any;
   errorCode?: apiErrors // this is the change
}

// example of invalid response
const invalidResponse: IApiResponse = {
   status: false,
   payload: {foo: 'bar'},
   errorCode: 'something not in the enum',
};

// valid response
const validResponse: IApiResponse = {
   status: false,
   payload: {foo: 'bar'},
   errorCode: apiErrors.INVALID_SHAPE,
};

// another valid response with no errorCode specified
const anotherValidResponse: IApiResponse = {
   status: true,
   payload: {foo: 'bar'},
   // errorCode isn't included at all
};

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

Experimenting with NGXS selectors: A comprehensive guide

Hey there, I am currently utilizing the NGXS state management library in my application. I have a selector set up like this and everything seems to be functioning correctly. However, while testing the app, I encountered the following error message: "PrintI ...

Oops! The 'map' property cannot be found in the type 'Observable<User>'

In my online shopping project that combines Angular and Firebase, I implemented the AuthGuard to verify user login status before accessing various links including ./check-out. However, I encountered an issue with importing map for Observable.User. All comp ...

Guide to extracting the JSON array from a JSON object with Angular

In my angular application, I have made a call to the API and retrieved a JSON object in the console. However, within this JSON object, there are both strings and arrays. My task now is to extract and parse the array from the object in the console. The JSO ...

The specified property is not recognized by the type in TypeScript

I have set up a basic form with validation in Ionic 2. The form functioned properly when I used 'ionic serve' but encountered issues when running 'ionic run'. My suspicion is that the problem lies within my TypeScript code, specifically ...

Navigating through the key type within a mapped structure

I am working with a mapped type in the following structure: type Mapped = { [Key in string]: Key }; My understanding is that this setup should only allow types where the key matches the value. However, I have found that both of the cases below are permitt ...

Tips for maintaining the original data type while passing arguments to subsequent functions?

Is there a way to preserve generic type information when using typeof with functions or classes? For instance, in the code snippet below, variables exampleNumber and exampleString are of type Example<unknown>. How can I make them have types Example& ...

Error TS7053 occurs when an element is given an 'any' type because a 'string' expression is being used to index an 'Object' type

When attempting to post data directly using templateDrivenForm and retrieve data from Firebase, I encountered the following type error message. Here are the relevant parts of my code: // Posting data directly using submitButton from templateDrivenForm onC ...

Error in TypeScript while running the command "tsd install jquery" - the identifier "document" could not be found

Currently, I am facing an issue with importing jQuery into my TypeScript project. In order to achieve this, I executed the command tsd install jquery --save, which generated a jquery.d.ts file and added /// <reference path="jquery/jquery.d.ts" /> to ...

What could be causing my "Swiper" component to malfunction in a TypeScript React project?

In my React project, I decided to incorporate the Swiper library. With multiple movie elements that I want to swipe through, I began by importing it as follows: import Swiper from 'react-id-swiper'; Utilizing it in my code like this: <div cla ...

The dynamically rendered component cannot be assigned to the type 'IntrinsicAttributes & ContentOutlineProps & ContentBrainstormProps'

I am facing an issue on my page where a <SideBar /> component is causing a Typescript error with the setActivePage hook. The error message points to a specific line in my code: const Content: (({ question_blocks, }: ContentBrainstormProps) => JSX. ...

Angular 4 allows you to assign unique colors to each row index in an HTML table

My goal is to dynamically change the colors of selected rows every time a button outside the table is clicked. I am currently utilizing the latest version of Angular. While I am familiar with setting row colors using CSS, I am uncertain about how to manip ...

How do I go about mocking a function from a third-party nodejs module when using TypeScript with jest?

I need help with mocking a function from a third-party node module in jest, specifically the fs.readFileSync() function. I have come across several examples online, but I haven't found one that incorporates TypeScript. To illustrate my question, I hav ...

Adjusting an item according to a specified pathway

I am currently working on dynamically modifying an object based on a given path, but I am encountering some difficulties in the process. I have managed to create a method that retrieves values at a specified path, and now I need to update values at that pa ...

There seems to be an issue with Firebase authentication on firebase-admin in node.js. Your client is being denied permission to access the URL "system.gserviceaccount.com" from the server

Issue I've been utilizing Firebase auth on my client and using firebase-admin to verify on the server. It was functioning well until I decided to migrate to a different server, which caused it to stop working. The crucial part of the error message i ...

Dynamic starting point iteration in javascript

I'm currently working on a logic that involves looping and logging custom starting point indexes based on specific conditions. For instance, if the current index is not 0, the count will increment. Here is a sample array data: const data = [ { ...

Issue with Moment Js: Unable to change date with time zone function

Trying to convert a UTC date and time to local time ("Europe/Paris") using moment's timezone function, but encountering issues. The code I am using is: var m = moment.tz(this.startTime, 'Europe/Paris'); this.startTime = m.format("YYYY-MM-DD ...

Ways to attain a similar format - input map

After pressing the save button, I am aiming to achieve the following effect: "timeTable":{ "0": [{"from":"08:00","to":"12:00"}, {"from":"14:00","to":"18:20&q ...

When working in React, I often encounter the frustrating TypeError: Cannot read property 'content' of undefined error

Trying to customize a React project, I attempted to add a class to a div using the following code: <div className={styles.content}> In the case of deleting the Data Source, you will lose all configuration sett ...

Continuously extract information by filtering through the array

Currently, I am in the process of developing an idle RPG game using Angular. One of the features I have implemented is a console log that displays events such as Damage Dealt and Experience Earned. In order to manage messages efficiently, I have created a ...

Error in Next.js when trying to use Firebase Cloud Messaging: ReferenceError - navigator is not defined in the Component.WindowMessagingFactory instanceFactory

Currently, I am in the process of setting up push notifications with Firebase in my next.js application. I have been following a guide from the documentation which you can find here: https://firebase.google.com/docs/cloud-messaging/js/receive?hl=es-419 Ho ...