TS2339: Issue with TypeScript binding for redux types

While diving into TypeScript for the first time, I encountered error TS2339 as I attempted to create a typed redux reducer. The error message is as follows:

https://i.sstatic.net/UyRM0.png

Am I missing something in my usage of the typescript pipe operator? Appreciate any guidance!

sampleActionTypes.ts:

export interface Data {
  allIds?: number[];
  byId?: object;
}

interface IncrementCount {
  type: string;
}

interface ReceiveData {
  type: string;
  data: Data;
}

export type SampleActionTypes = ReceiveData | IncrementCount;

sampleReducer.ts:


export interface SampleState {
  count: number;
  data: Data;
}

const initialState = {
  count: 0,
  data: {},
};

const sample = (state = initialState, action: SampleActionTypes): SampleState => {
  switch (action.type) {
    case 'INCREMENT_COUNT': {
      const newCount = state.count + 1;
      return {
        ...state,
        count: newCount,
      };
    }
    case 'RECEIVE_DATA':
      return {
        ...state,
        data: action.data, // encountering an error at this point
      };
    default:
      return state;
  }
};

export default sample;

Answer №1

export type SampleActionTypes = ReceiveData | IncrementCount;

The data property is not present in the IncrementCount type.

You have a few options:

a) Use type assertion:

(action as ReceiveData).data

b) Implement "discriminated union" (previously referred to as "branded" types)

interface IncrementCount {
  type: 'INCREMENT_COUNT';
}

interface ReceiveData {
  type: 'RECEIVE_DATA';
  data: Data;
}

TypeScript should be able to infer the correct type through duck-typing

c) Utilize type guards

function isReceiveDataAction(x: any): x is ReceiveData {
  return x.type === 'RECEIVE_DATA'
}

function isIncrementAction(x: any): x is IncrementData {
  ...
}

if (isIncrementAction(action)) {
  // action is IncrementData
} else if (isReceiveDataAction(action)) {
  // action is ReceieveData
}

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

Leveraging the cypress chainable command within an if/else statement

Can anyone offer guidance on how to incorporate chainable commands with if/else logic without duplicating code? Specifically, I want to avoid repeating .trigger('focus', {force: true}).click({force: true}); in both the if and else statements. I h ...

Removing punctuation from time duration using Moment.js duration format can be achieved through a simple process

Currently, I am utilizing the moment duration format library to calculate the total duration of time. It is working as expected, but a slight issue arises when the time duration exceeds 4 digits - it automatically adds a comma in the hours section (similar ...

guide on implementing optional URL parameters in NestJS

Currently, I am in the process of transitioning to the Nestjs library for our backend service. I am looking to create a route that includes 2 optional parameters in the URL. Here's what I have in mind: /route/:param1/config/:OptionalParam3?/:Optional ...

Create a simulated API in Angular by utilizing JasonPlaceholder to retrieve information upon clicking a button

I am currently developing a dummy API using jsonplaceholder. I have managed to retrieve all posts after clicking a button, but now I want to display the user ID and title by default on page load. Additionally, when clicking on a post's title, I would ...

Intellij IDEA does not offer auto-completion for TypeScript .d.ts definitions when a function with a callback parameter is used

I've been working on setting up .d.ts definitions for a JavaScript project in order to enable auto-completion in Intellij IDEA. Here is an example of the JavaScript code I'm currently defining: var testObj = { tests: function (it) { ...

Delay the execution of a JavaScript method that resolves a promise

Currently, I am delving into the world of Angular 2, typescript, promises, and more. I've set up a small application for developer tools with a service that simply returns hard-coded data. This setup is purely for testing purposes. I want to introduc ...

When attempting to deploy my app, I encountered a CORS error with Nest.js

Currently, I am in the process of building a Nest.js - React.js application. However, I am encountering a cors error despite having cors enabled in my main.ts file of Nest.js. While my application functions smoothly on localhost and an IP address in produ ...

Issue with Framer-motion animation not triggering on exit

Here is a link to the code sandbox In this gif demonstration, it's evident that the notifications are not triggering the exit animation when removed from the DOM (usually after 6 seconds). Why is this happening? I've followed all the suggestion ...

Angular Ionic calendar date selector

I'm encountering an issue while trying to implement a time picker with a minimum and maximum hour range from 10:00 am to 10:00 pm. Unfortunately, I have discovered that I cannot achieve this using the ion-datetime component. Are there any alternative ...

Loading preferred routes in Angular 6+ Universal for faster performance

In my Angular 7 application, I have Angular Universal set up with Express and I am also utilizing Angular Routing. My goal is to have only the pre-login routes (marketing views) rendered server-side, while post-login routes are loaded using traditional cli ...

What is the method for defining a mandatory incoming property in an Angular2 component?

In my current project, I am developing a shared grid component using Angular2 that requires an id property. export class GridComponent { @Input() public id: string; } I'm looking for a way to make the id property mandatory. Can you help me with ...

Is there a method (hack) to instantiate an instance of class `T` within a generic class?

Is there a way or workaround to instantiate an object of type T within a generic class? type Foo = { /*...*/ }; class Bar < T extends Foo > { public readonly foo: T; public constructor( init?: { foo: T } | undefined ) { this.f ...

When trying to map a nullish object, TypeScript throws an error

When I try to map a nullish object, I encounter an error: Object is possibly 'undefined'.ts(2532) Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Partial<Point ...

Change the color of certain rows in the table

I'm currently working on a project using Angular4 and ngx-datatable, so my .html file looks like this: <ngx-datatable> <ngx-datatable-column> <ng-template> ... {{row.value}} My goal is to check the value of eac ...

Is it possible to utilize an @Input() in Angular with multiple types?

Is it possible for a parent component to pass an object in @Input to the child component that may not always be the same? For instance, can I use: @Input() obj: string | number; In my scenario, I have two different objects as potential inputs: @Input() ob ...

A guide on incorporating an array as the initial data in redux by utilizing the createEntityAdapter() function

Looking to initialize an array as the initial data to display some default information. eventSlice.ts import { createEntityAdapter, createSlice, EntityAdapter, } from "@reduxjs/toolkit"; import { RootState } from "../store"; ex ...

Best practices for transitioning a project from TypeScript 3 to TypeScript 4?

I am looking to upgrade my large monorepo, which was built using lerna, React, and TypeScript 3.7 around 2-3 years ago. My goal is to update it to TypeScript 4.8. Are there any tools available that can help me analyze and identify potential breaking chan ...

Having difficulty converting string columns/data to numerical values when exporting an Ag-Grid table to Excel with getDataAsExcel function

I am having an issue with exporting data from my ag-grid table to excel using the API method getDataAsExcel. The problem arises because I have a column containing only string values, while all other columns are numeric and displayed in the ag-grid table a ...

Struggling to find a solution for directing to the featured homes page without the content overlapping with my navbar and search component. Any assistance would be greatly

Looking for assistance with routing to the featured homes page without the content overlapping my navbar and search component. I simply want it to direct to a new URL without importing the components unless specifically needed. Check out this link I suspe ...

Incorporating TypeScript's internal references

I am currently working on defining my own model interface that extends the Sequelize model instance. However, I am encountering difficulties in referencing the Sequelize interface within my code. Specifically, I receive an error stating "Cannot find name ...