Distinguishing between TypeScript versions 2.0.x and 2.1.x using type definitions and filtering with a switch/case statement

@ngrx/store (an observable redux implementation for angular (2) ) utilizes a specific pattern to assign the correct type to a reducer.

Check out the actual code here.

export const ActionTypes = {
  FOO:  type('foo'),
  BAR:  type('bar')
};

export class FooAction implements Action {
  type = ActionTypes.FOO;

  constructor(public payload: string) { }
}

export class BarAction implements Action {
  type = ActionTypes.BAR;

  constructor(public payload: number) { }
}

export type Actions
  = Foo
  | Bar;

This also includes a sample reducer:

export class SomeReducerState {
  foo: string;
  bar: number;
}

const initialState = {
  foo: undefined,
  bar: 0
};

export function someReducer(
  state: SomeReducerState = initialState,
  action: some.Actions
): SomeReducerState {

  switch (action.type) {
    case some.ActionTypes.FOO:
      return Object.assign({}, state, { foo: action.payload });
    case some.ActionTypes.BAR:
      return Object.assign({}, state, { bar: action.payload });
    default:
      return state;
  }

}

In TypeScript 2.0.x, the switch/case structure was used to determine the proper type for action.payload. For example, inside case some.ActionTypes.FOO, action.payload was assigned as string, while in BAR it was number. However, with TypeScript 2.1.x, it appears to default to any. Is there a workaround to achieve the same outcomes in 2.1.x? Or is it potentially a bug?

Answer №1

One method is to utilize the readonly attribute in conjunction with the type property. This approach also eliminates the need for the type utility function to coerce string types.

For the complete code, click here.

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

Exploring the Yahoo Finance Websocket with Angular

Upon visiting the Yahoo finance website (for example, ), I noticed that the page establishes a WebSocket connection. The URL for this WebSocket is wss://streamer.finance.yahoo.com/ I'm currently working on a small project where I need to retrieve dat ...

Embark on a journey through a preorder traversal of a Binary Tree using TypeScript

Hello! I've been tasked with creating a function that iterates over a binary tree and returns all its values in pre-order. Here is the code snippet: interface BinTree { root: number; left?: BinTree; right?: BinTree; }; const TreePreArray ...

When using TypeScript and Material UI, it is important to assign a value to boolean attributes

Trying to implement Material UI code with Typescript for a DisplayCard component, but encountering an error message: (34,23): Value must be set for boolean attributes. The challenge lies in identifying which attribute value is missing... Here is the samp ...

Angular data binding with an object instead of an array list

Currently, I am implementing Angular and attempting to iterate through an object. Data in JSON format employee {"fName":"mike","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ebb3b3b3b3b3b3b3b3ab83849f868a8287c588848 ...

Unlocking the full potential of Ionic 4 with push notifications, omitting

Currently, I am encountering an issue where I need to disable the display of notification alerts (local notification) while the application is running in the foreground on both Android and iOS. I only want to capture the push notification in the code witho ...

Invalid component prop provided to ButtonBase in Material UI. Ensure that the children prop is correctly rendered in this custom component

Forgive me for asking a basic question, as I am not the most proficient frontend developer and have searched extensively online. Whenever I inspect my frontend application in Chrome, I keep encountering this error. (3) Material-UI: The component prop pro ...

Enabling specific special characters for validation in Angular applications

How can we create a regex pattern that allows letters, numbers, and certain special characters (- and .) while disallowing others? #Code private _createModelForm(): FormGroup { return this.formBuilder.group({ propertyId: this.data.propertyId, ...

What is the best way to transform a JavaScript object into an array?

Here is the information I have: {product_quantity: {quantity: 13, code: "AAA", warehouse: "1000",}} The product_quantity field is part of a JSON object in a MongoDB database. I am looking to convert it into this format: {"produ ...

Why is the mat-toolbar and mat-toolbar-row in the footer (shared) component of Angular 6 not showing up correctly, despite no error being reported?

Despite reviewing similar questions, I have not been able to find a solution for my specific issue. I have searched through the following links but failed to find a solution: Angular Material v6 Mat-Footer - "Cannot read property 'template' of ...

What is the best way to expose the "nuxtServerInit" action for Nuxt.js when using dynamic modules exclusively?

According to this answer, the code snippet below is taken from the official documentation of vuex-module-decorators // @/store/index.ts import Vuex from 'vuex' const store = new Vuex.Store({ /* Ideally if all your modules are dynamic then ...

Master Angular Autocompletion

Looking to add a filter autocomplete feature but unsure of how to implement it. Any assistance would be greatly appreciated! I've come across some examples, but they don't quite fit my needs. Here's the snippet of code: <mat-form-field c ...

Modifications to the toolbar styling are made by the Angular Material mat-form-field

Having some trouble creating an input field in my component alongside a mat-toolbar element. When I try to insert a mat-form-field, it ends up messing with the styling of the mat-toolbar. I've been unable to pinpoint exactly where the issue lies (if ...

Upon being redirected to a different route, it immediately navigates back to the previous page

Whenever we redirect to a route using an anchor tag with [routerLink], or through the code using: router.navigate(['/path']) For example, if we redirect to the extractedData page from the result page, it initially shows the extractedData page b ...

Bringing in a script and invoking a function on a specific variable

As a newcomer to Typescript, I've been experimenting with some code I came across online to enhance the appearance of links on my website. <script src="https://wow.zamimg.com/widgets/power.js"></script> <script>var wowhead_tooltips ...

What is preventing Angular from letting me pass a parameter to a function in a provider's useFactory method?

app.module.ts bootstrap: [AppComponent], declarations: [AppComponent], imports: [ CoreModule, HelloFrameworkModule, ], providers: [{ provide: Logger, useFactory: loggerProviderFunc(1), }] ...

get a collection of chosen files in angular 7 and save them to

Greetings, I am currently working on a project and encountering an issue. I need to download multiple selected files from a list, but despite my efforts in searching for a solution, I have been unable to find one. While I can successfully download single f ...

Vue Deep Watcher fails to activate when the data is altered

While the countdown timer is functioning properly, it seems that the deep watcher is not working as expected. Despite attempting to log the new value of seconds in the console, it does not display anything even though the countdown timer continues to funct ...

Issue with parsing string data from API call in Angular (Web Core 3)

Controller code: [Route("api/[controller]")] [ApiController] public class CustomController : ControllerBase { ApplicationDbContext dbContext = null; public CustomController(ApplicationDbContext ctx) { dbContext = ctx; } ...

Obtain the query parameter before undergoing redirection within Angular version 14

In my Angular application, I am facing a challenge where I need to display a specific message to the user once they click on a link that has been sent to them via email. The link is intended to open a page within the app at the URL: "localhost:8080/?d ...

Exploring the concept of asynchronous subscriptions in Angular

My current issue seems to be related to asynchronous programming, specifically with the subscription not running at the desired time. I typically approach this problem from both the user's and developer's perspectives. User's Perspective: ...