Utilizing enumerations to define properties within a class

In my current scenario, I have the following set of definitions:

enum AccountTypes {
  CHECKING = 'Checking',
  SAVINGS = 'Savings',
}

export class BankAccount {
  id: number;
  label?: string;
  type: AccountTypes;

  constructor(init?: Partial<BankAccount>) {
    Object.assign(this, init);
  }
}

... when attempting to perform the following action:

const account = {
  id: 1,
  label: 'John Doe: Chase Checking ****1892',
  type: 'CHECKING',
};
const something = new BankAccount(account);

An error is encountered stating:

Types of property 'type' are incompatible. Type 'string' is not assignable to type '"CHECKING" | "SAVINGS" | undefined'.

Further experiments were conducted using:

export class BankAccount {
  id: number;
  label?: string;
  type: keyof typeof AccountTypes;

  constructor(init?: Partial<BankAccount>) {
    Object.assign(this, init);
  }
}

However, this approach did not yield desired results.

Note:

This particular case presents a unique challenge. It involves defining a `js` file with specific logic for use in mock tests. Essentially, it necessitates translating plain object data (resembling server responses) into test scenarios, leading to the aforementioned compatibility issue.

Answer №1

The issue with the initial approach is trying to pass a string instead of an enum member as expected.

As for the second approach, it fails because "CHECKINGS" is passed instead of "Checking" in the case.

To resolve this issue, you have several options:

1. Utilize an enum member:

const account = {
  id: 1,
  label: 'John Doe: Chase Checking ****1892',
  type: AccountTypes.CHECKING,
};
const something = new BankAccount(account);

2. Maintain the same typing as used in the second approach (keyof typeof AccountTypes):

const account = {
  id: 1,
  label: 'John Doe: Chase Checking ****1892',
  type: 'Checking',
};
const something = new BankAccount(account);

3. Create a type alias:

type AccountTypes = 'Checking' | 'Savings';

const account = {
  id: 1,
  label: 'John Doe: Chase Checking ****1892',
  type: 'Checking',
} as const;

// or

const account = {
  id: 1,
  label: 'John Doe: Chase Checking ****1892',
  type: 'Checking' as AccountTypes,
};

// or

const account: Partial<BankAccount> = { // It would be better to create an interface here
  id: 1,
  label: 'John Doe: Chase Checking ****1892',
  type: 'Checking',
};

const something = new BankAccount(account);

If considering using enums, it's advisable to employ const enum for complete removal during build generation.

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

No updates found (Angular)

When a button is clicked, a test method is triggered with i as the index of an element in an array. The test method then changes the value of the URL (located inside the sMediaData object) to null or '' and sends the entire sMediaData to the pare ...

Combining Babel with Typescript, utilizing NPM modules, and optimizing with Webpack

Hey there! I've been trying to include Angular in my TypeScript script, but unfortunately I keep encountering this error: error TS2307: Cannot find module 'angular'. I have attached my webpack configuration file below: context: __dirname ...

The value returned by UseSelector is not defined

this code snippet is responsible for monitoring the state of a shopping cart that contains various bets placed by the user const { games } = useSelector((state: any) => state.cart) which is then passed to another component like this <AppRecentUserG ...

Declaring a Static Method in TypeScript within a React Functional Component

I am attempting to access static methods from my functional component in React. Below is a brief example of what I am trying to achieve (it works in regular JavaScript). The issue arises on line 10 with the code const x = ... TS2339: Property 'GetM ...

Angular: Modify parent component's field using route

Hello everyone! I'm seeking assistance. In my Angular 10 application, I have a component called A. Within this component, there is a <router-outlet> and routes defined in the routes.ts file. My goal is to modify a variable (field) inside comp ...

Angular5+ Error: Unable to retrieve summary for RouterOutlet directive due to illegal state

When attempting to build my Angular App using ng build --prod --aot, I consistently encounter the following error: ERROR in : Illegal state: Could not load the summary for directive RouterOutlet in C:/Path-To-Project/node_modules/@angular/Router/router.d. ...

Resolving TypeScript Problem: Showing Error Alerts from React Hook Form

Currently, I am developing a registration form using react-hook-form within a React application. The form I'm working on includes validation for various fields, and my goal is to show error messages for each field. However, I have hit a bump in the ro ...

Create multiple instances of a component in a dropdown menu using different datasets in Angular 5

Outlined below is the structure of my drop-down list: Companies > Depots Each company has multiple depots. I have developed a component for companies, and upon clicking on a company (menu item), an HTTP request is made to bring all companies which are ...

Oops! Looks like there was an issue with parsing the module. It seems there is an unexpected character '@' in the file. Make sure you have the proper loader configured to handle this file type

Angular version: 14.2.7 I added a unique CSS library to my Angular project that is not publicly available. After adding it to app.module.ts: import { SapphireButtonModule } from '@sapphire-angular/core'; imports: [ SapphireButtonModule, ...

`Understanding the outcome type by assessing the (potential) attributes with TypeScript`

Here is a detailed example of a problem with some code: type Mapper<T, R> = (data: T) => R; interface Config<T, R> { readonly mapper?: Mapper<T, R>; } function transform<T, R>(config: Config<T, R>, data: T) { return c ...

Why was the event handler attached and for what purpose does it serve in this particular location?

When using Typescript with JQuery, I encountered a strange issue where a click event seemed to be added multiple times each time the user opened a dialog. Despite creating a new SettingsDlog object for each dialog instance, the click event did not behave a ...

There seems to be a lack of information appearing on the table

I decided to challenge myself by creating a simple test project to dive into Angular concepts such as CRUD functions, utilizing ngFor, and understanding HttpClient methods (specifically get and post). After creating a Firebase database with an API key and ...

Using Conditionals in React Props

In the process of developing a component that requires two props, inside and position, I've encountered an interesting dilemma. When inside is set to true, then position is limited to left or bottom. However, if inside is set to false, then position c ...

Return a potential undefined output

I am working with a variable called root which could potentially be undefined. Its value is only determined at runtime. const root = resolvedRoot || await this.fileSystem.getCurrentUserHome(); console.log('root.uri = ' + root.uri); The existenc ...

Exploring nested promises in TypeScript and Angular 2

I have a method called fallbackToLocalDBfileOrLocalStorageDB, which returns a promise and calls another method named getDBfileXHR, also returning a promise. In the code snippet provided, I am unsure whether I need to use 'resolve()' explicitly o ...

The Mongoose getter function is triggering error TS2590 by generating a union type that is too intricate to be displayed

I've come across the TS2590: Expression produces a union type that is too complex to represent error while trying to compile TypeScript. The issue seems to be connected to the id's getter function idFromString, as removing the id getter prevents ...

"Angular EventEmitter fails to return specified object, resulting in undefined

As I work on a school project, I've encountered a hurdle due to my lack of experience with Angular. My left-nav component includes multiple checkbox selections, and upon a user selecting one, an API call is made to retrieve all values for a specific " ...

The name 'Map' cannot be located. Is it necessary to alter your target library?

After running the command tsc app.ts, an error occurs showing: Error TS2583: 'Map' is not recognized. Should the target library be changed? Consider updating the lib compiler option to es2015 or newer. I want the code to compile without any issu ...

The promise of returning a number is not compatible with a standalone number

I am currently working on a function that retrieves a number from a promise. The function getActualId is called from chrome.local.storage and returns a promise: function getActualId(){ return new Promise(function (resolve) { chrome.storage.syn ...

Using TypeScript to eliminate duplicate values when constructing an array with various properties

Recently, I received an array from an API that has the following structure: results = [ {name: 'Ana', country: 'US', language: 'EN'}, {name: 'Paul', country: 'UK', language: 'EN'}, {name: & ...