Union does not contain the specified property in Typescript

Here are the types that I have:


Foo {
    foobar: any
}

Bar {
    fooBarBar: any;
}

I want to use a function defined like this:

this.api.submit(param: Foo | Bar)

When trying to use it, I encountered an issue:

this.api.submit(param.foobar) // does not exist on Bar

Error: Property 'foobar' does not exist on type 'Foo| Bar'.
  Property 'foobar' does not exist on type 'Bar '

I thought TypeScript would automatically determine which model to use based on the union, so why am I getting this error?

To get around this issue, I found that using bracket notation param['foobar'] resolves the error.

Answer №1

Your explanation implies that the variable param can only be either of type Foo or Bar, leaving the compiler unable to determine which one it is when calling param.foobar.

If you wish to differentiate between the two, you could try something like this:

type Foo {
    kind: 'foo',
    foobar: any
}

type Bar {
    kind: 'bar',
    fooBarBar: any;
}
...
if (param.kind === 'foo') {
    param.foobar; // The if statement serves as a type guard for instances of Foo
}

Alternatively, if you intended for param to encompass both Foo and Bar, you would require intersection types, denoted by Foo & Bar.

Answer №2

Everything is operating as expected.

If a type can have either the property foobar or not, then you cannot guarantee that the property will exist.

This could lead to issues if you assume that it exists in every valid reference.

As a result, TypeScript raises an error.

You might consider specifying that Bar may have a (possibly undefined) foobar property:

Foo {
 foobar: any
}

Bar {
 foobar?: any;
 fooBarBar: any;
}

It's important to only use properties that are guaranteed to be present in all members of the union type.

In essence, think of the union type as an interface that includes all the shared properties.

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

Angular2 - Creating PDF documents from HTML content with jspdf

For my current project, I am in need of generating a PDF of the page that the user is currently viewing. To accomplish this task, I have decided to utilize jspdf. Since I have HTML content that needs to be converted into a PDF format, I will make use of th ...

Using TypeScript, Material UI introduces a new property to the primary object on the palette

Experimenting with the customization of MUI v5 theme has been a fun challenge in my current project. I have successfully tailored the theme to suit my requirements so far, but now I am faced with the task of adding a new property to the primary object defi ...

Title remains consistent | Angular 4

Struggling to change the document title on a specific route. The route is initially set with a default title. { path: 'artikel/:id/:slug', component: ArticleComponent, data: {title: 'Article', routeType: RouteType.ARTICLE, des ...

Apollo useQuery enables risky array destructuring of a tuple element containing any value

Currently, I am incorporating TypeScript into my project and have a GraphQL query definition that utilizes Apollo's useQuery. According to the documentation, the call should be typed, however, I am encountering an ESLint error regarding data being ass ...

Encountering an issue when attempting to attach an event listener to the entire document

I need help troubleshooting an issue with a function that is supposed to perform certain operations when the scrollbar is moved. I attached an event listener to the document using an ID, but it's resulting in an error. ERROR Message: TypeError: Canno ...

What is the best way to time a Google Cloud Function to execute at the exact second?

In my attempt to schedule a cloud function using the Pub/Sub trigger method along with crontabs, I realized that it only provides granularity to the nearest minute. However, for my specific application - which involves working with trades at precise time ...

Angular - Ensuring service completion before proceeding with navigation

I'm currently facing an issue where I need to populate data in a service before navigating, but the navigation is happening before the data is ready. Here's the code in my service: addToken(token) { this.cookieService.set( 'token', ...

Validate if the program is currently running as "ionic serve" before implementing a conditional statement

Is there a method to determine if the ionic serve CLI is currently active (indicating it's not running on a physical device) within the code and use it as a condition? My problem: I have a Cordova plugin that returns a response to Cordova. When usin ...

Disable all typings within a specified namespace for a specific file

I need to disable typechecking for a specific namespace called MyNamespace in a Typescript file. Is there a way to achieve this without affecting other files? ...

Is there a way to implement retry functionality with a delay in RxJs without resorting to the outdated retryWhen method?

I'd like to implement a retry mechanism for an observable chain with a delay of 2 seconds. While researching, I found some solutions using retryWhen. However, it appears that retryWhen is deprecated and I prefer not to use it. The retry with delay s ...

Advanced automatic type inference for object literals in TypeScript

When working with TypeScript, I often declare generic functions using the syntax: const fn: <T>(arg: T)=>Partial<T> While TypeScript can sometimes infer the type parameter of a function based on its parameters, I find myself wondering if t ...

Issue encountered while managing login error messages: http://localhost:3000/auth/login net::ERR_ABORTED 405 (Method Not Allowed)

I am working on the /app/auth/login/route.ts file. import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs' import { cookies } from 'next/headers' import { NextResponse } from 'next/server' export async functi ...

What causes the return value of keyof to vary in this particular case?

type AppleNode = { type: 'Apple' name: string score: number } type BananaNode = { type: 'Banana' id: number score: number } type FruitNodes = AppleNode | BananaNode type fruitTest = { [P in keyof FruitNodes]: 21 } // Th ...

Creating personalized breakpoints in Material UI using TypeScript

When using the createMuiTheme() function, you have the ability to update breakpoint values like this. const theme = createMuiTheme({ breakpoints: { values: { xs: 0, sm: 600, md: 960, lg: 1280, xl: 1920, }, }, }) ...

The SideNav SpyOn feature failed to locate the specified method

In the test project I am working on, there is a side navigation menu. I need to create a simple test to verify that when I click the button, the sidenav opens or closes. The AppComponent interacts with the sidebar through its dependency, sidenavbar. it(&a ...

How to easily deactivate an input field within a MatFormField in Angular

I've come across similar questions on this topic, but none of the solutions seem to work for me as they rely on either AngularJS or JQuery. Within Angular 5, my goal is to disable the <input> within a <mat-form-field>: test.component.h ...

Error in Redux reducer file caused by an incorrect data type in action.payload

I have encountered a type error in my reducers' file where it says that my 'Property 'address' does not exist on type 'number | { connection: boolean; address: string; }'. This issue is arising in my React application while us ...

Setting up TypeScript in Jest without the need for webpack

Currently, I'm developing an NPM module using TypeScript without the use of Webpack for compiling scripts. I need some guidance on configuring Jest to properly run tests with TypeScript files. Any recommendations? // test.spec.ts import {calc} from ...

Error encountered while upgrading to Angular 5: splitHash issue

Currently in the process of transitioning from Angular 4.x to 5.x, I have encountered the following error: main.81bcdf404dc22078865d.bundle.js:1 Uncaught TypeError: i.splitHash is not a function at Object.t.parseUrl (main.81bcdf404dc22078865d.bundle.js:1) ...

Experiencing problems with React createContext in Typescript?

I've encountered a strange issue with React Context and Typescript that I can't seem to figure out. Check out the working example here In the provided example, everything seems to be working as intended with managing state using the useContext ...