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

Is there a distinction between Entity[] and array<Entity> in TypeScript?

Everything in the title, for example people: Person[]; people: Array<Person>; What sets them apart? Is there a preferred approach? Note: I couldn't find any guidance on this and I've encountered both in code. ...

Add a service to populate the values in the environment.ts configuration file

My angular service is called clientAppSettings.service.ts. It retrieves configuration values from a json file on the backend named appsettings.json. I need to inject this angular service in order to populate the values in the environment.ts file. Specific ...

Tips for implementing a cascading dropdown feature in Angular 7 Reactive Formarray: Ensuring saved data loads correctly in the UI form

I recently found a helpful guide on stackoverflow related to creating cascading dropdowns in an Angular reactive FormArray, you can check it out here After following the instructions, I managed to achieve my desired outcome. However, I now face a new chal ...

Handling errors within classes in JavaScript/TypeScript

Imagine having an interface structured as follows: class Something { constructor(things) { if (things) { doSomething(); } else return { errorCode: 1 } } } Does this code appear to be correct? When using TypeScript, I en ...

What is the proper way to combine two arrays containing objects together?

I am faced with the challenge of merging arrays and objects. Here is an example array I am working with: [ { name: "test", sub: { name: "asdf", sub: {} } }, { name: "models", sub: {} } ] ...

Tips for sending arguments to translations

I am currently implementing vuejs 3 using TS. I have set up my translation files in TypeScript as shown below: index.ts: export default { 'example': 'example', } To use the translations, I simply do: {{ $t('example') }} N ...

Issue with Typescript typing for the onChange event

I defined my state as shown below: const [updatedStep, updateStepObj] = useState( panel === 'add' ? new Step() : { ...selectedStep } ); Additionally, I have elements like: <TextField ...

A step-by-step guide on setting up a database connection with .env in typeorm

I encountered an issue while attempting to establish a connection with the database using ormconfig.js and configuring .env files. The error message I received was: Error: connect ECONNREFUSED 127.0.0.1:3000 at TCPConnectWrap.afterConnect [as oncomplete] ( ...

Struggling to properly test the functionality of my NgForm call in Angular2+

I've been trying to test the login functionality by inputting username and password in an NgForm, but I keep encountering unsuccessful attempts. Is there a vital step that I may be overlooking? Currently, I'm facing this error message: Chrome 6 ...

What is the best method to publish my npm package so that it can be easily accessed through JSDelivr by users?

I've been working on creating an NPM package in TypeScript for educational purposes. I have set up my parcel configuration to export both an ESM build and a CJS build. After publishing it on npm, I have successfully installed and used it in both ESM-m ...

``There seems to be an issue with the Deno logger FileHandler as it

I am currently in the process of setting up loggers for an application. I have a handler named console which logs every event to the console. Additionally, there is a handler called app that is supposed to log all events to a file. While the logs are succ ...

Is it possible to invoke a component's function within the click function of a Chartjs chart?

How do I trigger a function in my Component from an onclick event in my chart.js? export class ReportesComponent implements OnInit { constructor(public _router: Router, private data: ReporteService) {} this.chart = new Chart('myChart', { ...

Error in TypeScript when using keyof instead of literal in type pattern.Beware of TypeScript error when not

let c = { [X in keyof { "foo" }]: { foo: "bar" } extends { X } ? true : false }["foo"]; let d = { foo: "bar" } extends { "foo" } ? true : false; c and d should both return true, but surprisingly, c is eval ...

Solving the issue where the argument type is not assignable to the parameter type

I am attempting to filter an array of objects in React using TypeScript and encountered this error. Below is my interface, state, and function: TS2345: Argument of type '(prev: IBudget, current: IBudget) => IBudget | undefined' is not assigna ...

Update the mandatory fields in the required interface to extend to another interface, while ensuring that all subfields become

Currently, I have defined 2 interfaces: interface BattleSkills { strength: number; armor: number; magic_resistance: number; health: number; mana: number; intelligence: number; accuracy: number; agility: number; critical_damage: number; } ...

Execute a Typescript function where parameters are passed to another function

In my coding project, I came across a situation where I needed to write a method in Typescript. This method should allow me to run some checks and, if those conditions are met, return the result of another method. What I want is to pass a method along with ...

IntelliJ is indicating a typescript error related to react-bootstrap-table-next

Working with react-bootstrap-table-next (also known as react-bootstrap-table2) has been causing a Typescript error in my IntelliJ environment, specifically on the validator field within my column definition. Despite trying various solutions, such as adding ...

What are some effective ways to utilize the data gathered from a subscribe() method in a different

handleKeyUp(event: any): void { this.technologiesService.retrieveData(event.target.value) .subscribe(data => { this.myResults = data; }); } The result of data is: I want to assign data as a property for later use. I've attempted ...

Unable to display grid items in React material-ui grid list

export interface FlatsGridProps { flats: IClusterFlats[]; } export const FlatsGrid: React.StatelessComponent<FlatsGridProps> = (props: FlatsGridProps) => { if (props.flats.length === 0) { return (<div> empty </di ...

Exploring the latest upgrades in React 18 with a focus on TypeScript integration

I am currently working on a complex TypeScript project with React and recently made the decision to upgrade to the new version of React 18. After running the following commands: npm install react@18 npm install react-dom@18 npm install @types/react-dom@18 ...