How the addition of a type union allows it to be assigned to AnyAction

Struggling with Redux code, I've encountered a peculiar behavior regarding type assignment that has left me puzzled.

In the following code snippet, it's clear that you cannot assign anyaction to iaction. Yet, surprisingly, assigning anyaction to iaction2 works without any issues. Despite attempting to adhere to the "Assignment Compatibility" part of the specification, I can't quite grasp the reason behind this inconsistency.

What exactly is happening here? It seems apparent that there are instances of type AnyAction that cannot be assigned to IAction2.

export interface ILoadUserBegin {
    type: "LOAD_USER_BEGIN";
}

export interface ILoadUserSuccess {
    type: "LOAD_USER_SUCCESS";
    response: number;
}

type IAction = ILoadUserSuccess;
type IAction2 = ILoadUserBegin | ILoadUserSuccess;

// these are redux types

interface Action {
  type: any;
}

interface AnyAction extends Action {
  [extraProps: string]: any;
}

// tests

let iaction: IAction = { type: "LOAD_USER_SUCCESS", response: 2 };
let iaction2: IAction2 = { type: "LOAD_USER_BEGIN" };
let anyaction: AnyAction = { type: "foo" };

// ERROR
// Type 'AnyAction' is not assignable to type 'ILoadUserSuccess'.
// Property 'response' is missing in type 'AnyAction'.
iaction = anyaction;  

// But this is OK!
iaction2 = anyaction;

Answer №1

First and foremost, it's important to note that Action can be assigned to ILoadUserBegin

let iaction1: ILoadUserBegin = anyaction;  // This is valid

Therefore, it should come as no surprise that it can also be assigned to a union type which includes ILoadUserBegin as one of its components.

The following question arises: Why can a variable of type Action be assigned to ILoadUserBegin?

This all boils down to the fact that Action has a type property with a declared type of any.

any is a unique type that is compatible with everything; it essentially bypasses type checking, making {type: any} type compatible with {type: "LOAD_USER_BEGIN"} type.

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

Customizing Material UI Select for background and focus colors

I am looking to customize the appearance of the select component by changing the background color to "grey", as well as adjusting the label and border colors from blue to a different color when clicking on the select box. Can anyone assist me with this? B ...

Combine objects by selecting attributes from multiple objects

declare type A = {type: 'TypeA', attr1: string} declare type B = {type: 'TypeB', attr2: string} declare type U = A | B When I use type X = Pick<U, 'type'>, I get: { type: 'TypeA' | 'TypeB' } But I a ...

What is the syntax for defining a generic type in TypeScript when using the property name "type"?

Is there a way to declare a generic type GetAppActions where if T is equal to trigger, only the trigger data property is displayed, and vice versa? type GetAppActionType = 'trigger' | 'action' interface AppActionInputField {} type GetA ...

How can I organize an array in JavaScript by date for presentation on a webpage?

Check out this code snippet: list.component.ts const data1 = [ { dateStart: "2020-02-14 00:00:01", name: 'Server1' }, { dateStart: "2020-02-13 14:00:01", name: 'Server1' }, ...

Performing a search through a string array and updating a specific portion of each string

I am faced with an array containing a long list of Strings, and my goal is to filter out all the strings that begin with 'INSERT ALL' and replace the number inside the parentheses with the string ' NULL' Here is the original array: le ...

Maintaining the essence of generics while encapsulating functions

I am currently facing a challenge in defining a function that can wrap any other function while maintaining the parameter types and return type. I have managed to achieve this when the function does not use generics, but I am encountering difficulties wi ...

Is the runTest.ts class in the vscode-test setup ever utilized in the project? Its purpose remains unclear even in the example project

Being a novice to Typescript, JavaScript, and VScode Extensions I have set up a vscode-test following the guidelines provided here: https://code.visualstudio.com/api/working-with-extensions/testing-extension#custom-setup-with-vscodetest Based on the hel ...

What is the process for exporting a class and declaring middleware in TypeScript?

After creating the user class where only the get method is defined, I encountered an issue when using it in middleware. There were no errors during the call to the class, but upon running the code, a "server not found" message appeared. Surprisingly, delet ...

Refresh a Google chart without having to reload the entire page

I currently have a button that allows me to refresh the data on my page in case there is new data available through an API. Although this button successfully refreshes my datatable, it does not redraw the Google charts I have integrated into my project usi ...

How to pass a function from mapDispatchToProps to a Container component in a React/Redux application

I am currently rendering the RootComponent: //RENDERING ROOT COMPONENT------------------------------------------------------------------------------- ReactDOM.render( <Provider store={store}> <RootComponent /> </Provider> ...

Tips for evaluating the stickiness of a block within a cell when it adheres to a mat-header-cell

I am working with an Angular table and facing an issue. How can I make the span element in the cells of the first column stick to the sticky mat-header-row when scrolling down the table? My requirement is for the span element to stay attached to the lower ...

Is Babel necessary for enabling JavaScript compatibility in my TypeScript React project, excluding Create React App?

This is the webpack configuration for my React project built in TypeScript, module.exports = { mode: 'development', entry: ['./src/main.tsx'], module: { rules: [ { // Rule for ts/tsx files only, no rule for js/js ...

Retrieve parent route parameters from a dynamically loaded route component

Struggling to access the parent route params in a lazy loaded route component using activatedRoute.parent.params. Despite this not working, I have managed to find a solution that involves fetching the value using an array index number which feels like a &a ...

Specialized type for extra restriction on enum matching

In my current project, I am dealing with two enums named SourceEnum and TargetEnum. Each enum has a corresponding function that is called with specific parameters based on the enum value. The expected parameter types are defined by the type mappings Source ...

Input the date manually using the keyboard

I am currently utilizing the rc calendar package available at https://www.npmjs.com/package/rc-calendar When attempting to change the year from 2019 to 2018 by removing the "9," it works as expected. However, when trying to delete the entire date of 1/15/2 ...

TypeScript PatchBaseline with AWS CDK

I am currently working with the AWS CDK and TypeScript, utilizing the @aws-cdk/aws-ssm library to create a PatchBaseline. While I have successfully created the Patch baseline, I'm encountering difficulties when attempting to define approvalRules. I ca ...

Issue with Jest/SuperTest Express integration tests: encountering "Can't set headers after they are sent" error when making requests to the same endpoint in multiple test cases

Dealing with a tricky situation here.. I'm currently in the process of writing integration tests for an Express (Typescript) app, using Jest and Supertest. My challenge lies in having multiple tests for the same endpoint, specifically to test respon ...

Is there a universal method to transform the four array values into an array of objects using JavaScript?

Looking to insert data from four array values into an array of objects in JavaScript? // Necessary input columnHeaders=['deviceName','Expected','Actual','Lost'] machine=['machine 1','machine 2&apo ...

What is the issue with this asynchronous function?

async getListOfFiles(){ if(this.service.wd == '') { await getBasic((this.service.wd)); } else { await getBasic(('/'+this.service.wd)); } this.files = await JSON.parse(localStorage.getItem('FILENAMES')); var ...

Solving problems with accessing global variables in React Redux

I'm currently working on implementing a global state in react-redux for my project. However, I've encountered an issue with retrieving updated values after dispatching an action to populate the global state for the User. Below are snippets of the ...