The Power of TypeScript's Union Types

Provided: Reducer only accepts one of the following actions:

interface ItemAction {
    type: 'ADD_TODO'|'DELETE_TODO'|'TOGGLE_TODO',
    id: number
}

interface QueryAction {
    type: 'SET_QUERY',
    query: string
}

I anticipate that the reducer code will resemble something like this:

if (action as ItemAction) {
   console.log(action.id); // TypeScript recognizes that "id" is accessible here
} else {
   console.log(action.query); // TypeScript recognizes that action belongs to type QueryAction and thus "query" is accessible here
}

How can I achieve this using TypeScript?

Answer №1

A simple way to tackle this problem is by leveraging the in operator:

let action: ItemAction | QueryAction = ...;
if ('id' in action) {
  // The type is identified as ItemAction
} else {
  // The type is recognized as QueryAction
}

If you encounter more intricate scenarios, you can implement type guards.

Answer №2

One way to manage this situation is by using a custom typeguard. Take a look at the following example:

function isItemAction(someAction: any): someAction is ItemAction {
  if(someAction.id !== undefined && typeof someAction.id === 'number') {
    return true;
  } else {
    return false;
  }
}

if (isItemAction(action)) {
  console.log(action.id); // TypeScript recognizes that "id" is accessible here
} 

There are a few key points to remember about typeguards: (1) they must use the "is" keyword in their language; (2) it is common practice to name them like I have done with isX; (3) TypeScript does not verify the accuracy of your evaluation logic, so it's important for you to ensure it is correct. This means that a typeguard which always returns true will be acceptable from TypeScript's perspective.

For further information on creating user-defined type guards, visit this link.

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

Creating a parameterized default route in Angular 2

These are the routes I've set up: import {RouteDefinition} from '@angular/router-deprecated'; import {HomeComponent} from './home/home.component'; import {TodolistComponent} from './todolist/todolist.component'; import { ...

Using Mat-Error for Two Way Binding leads to frequent triggering of ngModelChange事件

I am working with a mat input field that has two-way data binding using ngModel, and I want to add validation using mat-error and formControl. <mat-form-field [formGroup]="myForm"> <input matInput formControlName="myFormName" autocomplete="off" ...

What is the process for transitioning global reusable types to package types within turborepo?

When creating an app within the apps folder, a global.d.ts file is required with specific types defined like this: interface Window{ analytics: any; } This file should be designed to be reusable and placed in the packages/types directory for easy acce ...

Is there a way to automatically scroll to the bottom of a div when it first

Looking to enhance my application with a chat feature that automatically scrolls to the bottom of the chat page to display the latest messages. Utilizing VueJs: <template> <div id="app"> <div class="comments" ...

What is the best way to combine two responses and then convert them into a promise?

When making two calls, the firstCallData prints data fine. However, when I use + to merge the responses, it returns me the following Response. What is a better approach to achieve this task? main.ts let data = await this.processResponse(__data.Detail ...

Utilizing an AwsCustomResource in AWS CDK to access JSON values from a parameter store

I found a solution on Stack Overflow to access configurations stored in an AWS parameter. The implementation involves using the code snippet below: export class SSMParameterReader extends AwsCustomResource { constructor(scope: Construct, name: string, pr ...

`A bug in my Angular 4 application causes a TypeError when hosted on IIS`

After hosting an Angular 4 app on IIS, it seems there is an issue when accessing the app from machines other than the ones used for development. An error message " 'Uncaught TypeError: undefined is not a function' common.es5.js:3084" appears on t ...

Tips for customizing Material UI's styled() SVG icon to accept SVG icon as a react component:

Currently, I have functioning code that uses the "any" type for props. When transitioning to MUI v5 and using the mui v4 makeStyles, this approach raises compatibility issues that were not present before. // Import SVG Icons components import { ReactCo ...

After introducing 5 guard properties, the intersection of unions in Typescript breaks down

In TypeScript, I am attempting to create a class where properties are only accessible if another property has been checked on the class. This needs to be done in a generic manner to facilitate reuse across multiple classes. For instance, class Test { Fo ...

Steps for converting a tsx file into a js file in React

Currently, I am in the process of a React Project and have numerous tsx files that I aim to convert for utilization as JavaScript within my project. What would be the best approach to achieve this task? ...

Can you explain the distinction between Reflect.getMetadata and Reflect.getOwnMetadata?

Just like the title says, the reflect-metadata API comes with a method called getMetadata and another called getOwnMetadata. Can you explain the distinction between them? The same question applies to hasOwnMetadata, and so on. ...

An error persists in PhpStorm inspection regarding the absence of AppComponent declaration in an Angular module

After creating a new Angular application, I am encountering the issue of getting the error message "X is not declared in any Angular module" on every component, including the automatically generated AppComponent. Despite having the latest version of the An ...

What might be causing AngularJS to fail to display values when using TypeScript?

I have designed the layout for my introduction page in a file called introduction.html. <div ng-controller="IntroductionCtrl"> <h1>{{hello}}</h1> <h2>{{title}}</h2> </div> The controller responsible for handling th ...

component is receiving an incompatible argument in its props

I am facing a situation where I have a component that works with a list of items, each with an ID, and a filtering function. The generic type for the items includes an ID property that all items share. Specific types of items may have additional properti ...

Exploring Parquet Files with Node.js

Looking for a solution to read parquet files using NodeJS. Anyone have any suggestions? I attempted to use node-parquet but found it difficult to install and it struggled with reading numerical data types. I also explored parquetjs, however, it can only ...

Loading a Dynamic URL within a Component's template in Angular 2.0.0-rc.1

Is there a method for dynamically loading URLs in the templateUrl property? Similar to the code snippet below: @Component({ moduleId: module.id, selector: 'my-app', templateUrl: DynamicUrl, // Load DynamicUrl here styleUrls: [&ap ...

Troubleshooting Problem with Next.js 13 Integration, Supabase, and Server Actions in layout.tsx

I'm currently developing a Next.js 13 application and experimenting with managing user authentication through Supabase. I've encountered some challenges when attempting to verify if a user is logged in using an asynchronous function within my lay ...

Converting JavaScript object data to x-www-form-urlencoded: A step-by-step guide

I am trying to convert a JavaScript object into x-www-form-urlencoded. Is there a way to achieve this using Angular 2? export class Compentency { competencies : number[]; } postData() { let array = [1, 2, 3]; this.comp.competencies ...

Encountered an error stating "Cannot find module node:fs" while using eslint-typescript-import, eslint-import-resolver-typescript,

Challenge My attempt to configure path alias in my TypeScript project was met with failure. Two errors arose during the execution of npm start: Module not found: Error: Can't resolve '~/App' in 'D:\work\workbench\templa ...

Here is a guide on showcasing information obtained from ASP.NET API in Angular version 13

My goal is to fetch motorcycle data from a web API and showcase it in my Angular project. ASP.NET Framework Web API 4.7 Angular CLI: 13.3.7 Angular: 13.3.11 On the Web API end: Controller: [EnableCors(origins: "*", headers: "*", ...