Here's how to retrieve a property from a union type object in Typescript without the need for type casting

I am facing a scenario with various types:

export type a = {
  todo: string;
};

export type b = {
  id: number;
};

export type TodosAction = Action<string> & (a | b);

In addition, I have a function defined as follows:

function doSmth(action:TodosAction){
  switch(action.type){
    case "a":
      action.todo //TS error, doesn't exist
      (action as a).todo // Works fine this way
  }
}

The main concern is regarding accessing the todo property without needing to typecast using as.

Edit:

type Action<T>={
  type:T;
}

Answer №1

Ensure to include the type property in each interface within a union type:

export type x = {
  type: 'x';
  task: string;
};

export type y = {
  type: 'y';
  number: number;
};

The concept being used in Typescript is called Discriminated Union, which requires a specific string (or number) value for the type property in each type belonging to the union. In this scenario, the type property should have values of either 'x' or 'y'. This allows you to easily differentiate between the types in your function:

function performAction(action:TodosAction){
  switch(action.type){
    case "x":
      action.task; // no errors - action is an object of type 'x'
      break;
    case "y":
      action.number; // also no errors - action is an object of type 'y'
      break;
  }
}

Remember to use the break keyword in each case for proper functionality.

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

Tips for fixing TypeScript compiler error TS2339: Issue with accessing 'errorValue' property in Angular 5 project

Within a component, I have developed a function to manage errors returned from a Rest Service and determine the corresponding error message to display to the user. This method accepts an error object (custom data structure from the service), navigates to e ...

What is the best way to set a checkbox to null instead of false using Angular?

I am currently developing a filtering system that allows users to select different parameters to filter through a list of items. For instance, the item list could be a collection of dishes with filters represented as checkboxes labeled as vegan, vegetaria ...

The testString's dependencies are unresolved by Nest

Encountered Problem: Facing the following issue while running a unit test case Nest is unable to resolve the dependencies of the testString (?). Please ensure that the argument SECRET_MANAGER_SERVICE at index [0] is available in the context of SecretMa ...

Is it possible to combine TypeScript modules into a single JavaScript file?

Hey there, I'm feeling completely lost with this. I've just started diving into Typescript with Grunt JS and I could really use some assistance. I already have a Grunt file set up that runs my TS files through an uglify process for preparing the ...

Discovering the JavaScript source file for a package using WebStorm and TypeScript

In my TypeScript project, there is a usage of Express with the following method: response.send('Hello'); I am interested in exploring the implementation of the send() method. However, when I try to navigate to the source code by ctrl+clicking o ...

Creating a Prisma schema with a complex nested structure and incorporating an array of strings for a specific property

I'm trying to create a detailed Prisma schema for a product database that includes nested properties and an array of strings for image content. The structure I'm aiming for looks like this: interface Product { id: number; name: string; ...

An issue has occurred: Unable to access the 'seatsavailable' property of an undefined object

Currently, I am immersed in a project involving Angular 6 and utilizing the @Input and @Output decorators. In this scenario, I have the Bookride Component functioning as the parent component with RideDetails serving as the child component. Successfully tra ...

When setupFilesAfterEnv is added, mock functions may not function properly in .test files

Upon including setupFilesAfterEnv in the jest.config.js like this: module.exports = { preset: 'ts-jest', testEnvironment: 'node', setupFilesAfterEnv: ["./test/setupAfterEnv.ts"] } The mock functions seem to sto ...

"Optimize Your Workflow with the Virtual Assistant Bot Platform and Command Center

As I work on developing a Virtual Assistant for Microsoft Teams, I've noticed some limitations with using adaptive cards due to the version of Teams I'm working with. For example, the buttons always need to be placed at the end of the card. In se ...

Is there possibly a problem with GridActionsCellItem and its props?

I'm encountering a problem with passing props into the GridActionsCellItem within the '@mui/x-data-grid'; columns; { field: 'actions', type: 'actions', width: 80, getActions: (params: any) =&g ...

Issue with Typescript not recognizing default properties on components

Can someone help me troubleshoot the issue I'm encountering in this code snippet: export type PackageLanguage = "de" | "en"; export interface ICookieConsentProps { language?: PackageLanguage ; } function CookieConsent({ langua ...

Include a class in ul > li elements upon page load in Angular4

I attempted to add a class to each "li" element in an Angular4 page, but the class was not applied. Here is the relevant HTML code: <ul class="pagination"> <button class="previous" (click)="previous()">Previous</button> <button ...

Having trouble with filtering an array using the some() method of another array?

When utilizing the code below, my goal is to filter the first array by checking if the item's id exists in the second array. However, I am encountering an issue where the result is coming back empty. dialogRef.afterClosed().subscribe((airlines: Airli ...

Nested Tagged Union Types in Typescript

Imagine having the following types (syntax similar to Elm/Haskell): type Reply = LoginReply | LogoutReply type LoginReply = LoginSucceeded | AlreadyLoggedIn String When trying to represent this in Typescript using discriminated unions, a challenge arises ...

Is "await" considered as a reserved word in ReactJS when using TypeScript?

I am trying to implement async await in my code, but I keep getting an error that says await is a reserved word. Here is the snippet of my code: public componentDidMount() { this.startDrag(); } private startDrag = async () => { const eleme ...

Sticky header in React data grid

Is there a way to implement a sticky header for a data grid in react? I have tried various methods but haven't been able to figure it out. Any suggestions would be appreciated. You can find my code sandbox example here. #react code export const Styl ...

The typings for object properties in Typescript

I recently encountered a function call in my code: var myVar = myFunction({ property: 'prop', functionProperty() { console.log(this.property); }, functionProperty2() { this.functionProperty(); } }); I' ...

The specified file path '.../node_modules/@nomicfoundation/hardhat-core/src' could not be located

I have successfully set up a TypeScript hardhat project, but I encountered an issue in /***/node_modules/@nomicfoundation/hardhat-chai-matchers/src/tsconfig.json: { "extends": "../../../config/typescript/tsconfig.json", "compil ...

Best approach for managing Union Types in Angular 16 Templates / Utilizing Type Inference?

Currently, I'm immersed in a project using Angular 16 where my focus lies on applying a reactive declarative method. Oftentimes, I find myself working with Observables that emit varying data types - either successful data or an error object. Each ret ...

Exploring the functionality of the Angular snackbar feature

I have created a simple snackbar with the following code: app.component.ts: ngOnInit(){ this.dataService.valueChanges.pipe( filter((data) => data === true), switchMap(() => { const snackBarRef = this.matSnackBar.open ...