Exploring the differences in object shapes using TypeScript

I'm currently working on defining an object that has the ability to hold either data or an error.

export type ResultContainer = {
  data: any;
} | {
  error: any;
};

function exampleFunction():ResultContainer {
    return {
        data: 3
    }
}

However, when attempting to access the result of the function, I encounter the following issue:

const result = exampleFunction();
result.data = 23; // Property 'data' does not exist on type 'ResultContainer'. Property 'data' does not exist on type '{ error: any; }'

Could someone guide me on the correct way to access either 'data' or 'error'? Thank you!

Answer №1

Here is TypeScript's interpretation of your code:

const v = test();
// v: {data: any} | {error: any}
v.data = 23;
// There is a possibility that 'v' could be of type '{error: any}'
// If so, there may be a runtime error
// To avoid this error, let's throw a TS error now!

To prevent this from happening, you can use a type guard to narrow down the union type to a specific type that won't lead to a TS error:

const v = test();
// v: {data: any} | {error: any}
if ('data' in v) {
  // v: {data: any}
  v.data = 23;
  // no error will occur!
}

If you are confident that v will have a property named data, you can cast v during its declaration:

const v = (test() as {data: any});
v.data = 23;

You can experiment with this code on the typescript playground

Answer №2

Check out this implementation featuring a discriminated union structure (including the addition of a shared property called dataType in each union member):

export type Outcome = {
  dataType: "result",  
  resultData: any
} | {
  dataType: "failure",  
  errorMessage: any
};

function assess(): Outcome {
    return {
        dataType: "result",
        resultData: 5
    }
}

const res = assess();
if ("result" === res.dataType){
   res.resultData = 45;
}

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

Best Practices for Displaying Videos in Ionic 2

Can videos be properly integrated into Ionic pages? I'm encountering an issue where the buttons become unusable in fullscreen mode when using the html 5 video element. <video id="video1" width="100%" preload="metadata" controls webkit-playsinline& ...

Having trouble linking the date object with the default value of the date input field

Exploring how to set the default value of a date type input using property binding. Initially, I attempted to create a new date object in app.component.ts and then bind the [value] attribute of the date input to the currentDate property within app.compone ...

react state change not triggering re-render of paragraph

I recently started learning react and web development. To streamline my work, I've been using ChatGPT, but I'm facing an issue that I can't seem to solve. I'm trying to fetch movie descriptions from the TMDB API using movie IDs, but des ...

Converting Typescript fat arrow syntax to regular Javascript syntax

I recently started learning typescript and I'm having trouble understanding the => arrow function. Could someone clarify the meaning of this JavaScript code snippet for me: this.dropDownFilter = values => values.filter(option => option.value ...

Reattempting a Promise in Typescript when encountering an error

I am currently working on a nodeJS application that utilizes the mssql driver to communicate with my SQL database. My goal is to have a unified function for retrieving a value from the database. However, in the scenario where the table does not exist upon ...

typescript page objects in protractor are showing an undefined property

Hey there, I'm facing an issue while using POM in Protractor with TypeScript in Angular CLI. The error I'm encountering is "Cannot read property 'sendUsername' of undefined". Since I'm new to TypeScript, can someone guide me on how ...

Could you please tell me the type that is returned by the createClient function?

Despite being a TS newbie, I have been delving into writing small services using TS. Recently, I've been developing a CLI tool that leverages the power of node-redis, which is an exceptional redis client. The burning question on my mind is regarding ...

Exploring Angular 2 with Visual Studio 2015 Update 1 in the context of Type Script Configuration

After spending the last week attempting to set up and launch a simple project, I am using the following configuration: Angular 2, Visual Studio 2015 update 1, TypeScript Configuration In the root of my project, I have a tsconfig.Json file with the follow ...

Angular Universal involves making two HTTP calls

When using Angular Universal, I noticed that Http calls are being made twice on the initial load. I attempted to use transferState and implemented a caching mechanism in my project, but unfortunately, it did not resolve the issue. if (isPlatf ...

"Encountering a Bug in Angular 2 Related to Chart.js

I am currently in the process of developing a Twitter-style application using a Typescript/Angular2 front-end framework and a Node.js back-end. The foundation of my project is derived from Levi Botelho's Angular 2 Projects video tutorial, although I h ...

Difficulty encountered when trying to apply a decorator within a permission guard

I'm a newcomer to Nestjs and I am currently working on implementing Authorization using Casl. To achieve this, I have created a custom decorator as shown below: import { SetMetadata } from '@nestjs/common'; export const Permission = (acti ...

What allows the execution of "T[keyof T] extends Function" in TypeScript specifically for Strings?

Lately, I've been experimenting with type changes and I find myself puzzled when encountering code like the following: type DeepReadonly<T> = { readonly [k in keyof T]: T[k] extends Function?T[k]:DeepReadonly<T[k]> } // Let's defin ...

Unable to transfer variable from a function to the test in Protractor

Currently, I am working on a test to verify the amount of gold in my possession. The test is being conducted using TypeScript and Protractor. Within this testing scenario, I have a method named GetAmountOfChips: public static GetAmountOfChips(): PromiseL ...

Troubleshooting: Issue with Dependency Injection functionality in Angular 2 starter project

I’ve encountered a strange error whenever I attempt to inject any dependency TypeError: Cannot set property 'stack' of undefined at NoProviderError.set [as stack] (errors.js:64) at assignAll (zone.js:704) at NoProviderError.ZoneAwareError (zon ...

How to trigger a click event in React using TypeScript and material-ui library

Currently, I am facing an issue when trying to update the value of material-ui TextFields from the store. When manually typing inside the field, everything works fine as expected with the handleChange() and handleBlur() functions handling the events. Howev ...

Properly configuring paths in react-native for smooth navigation

When working on my React-Native project, I noticed that my import paths look something like this: import { ScreenContainer, SLButton, SLTextInput, } from '../../../../../components'; import { KeyBoardTypes } from '../../../../../enums ...

Converting a string to HTML in Angular 2 with proper formatting

I'm facing a challenge that I have no clue how to tackle. My goal is to create an object similar to this: { text: "hello {param1}", param1: { text:"world", class: "bla" } } The tricky part is that I want to ...

Receiving a conduit from the fuel supplier with only limited information on hand

I am designing a service that will utilize pipes as templates. In order to accomplish this, I require access to the registered pipes. The final code structure should resemble the following: @Injectable() class MyService { constructor(private injector ...

Error message occurs during compilation of basic Vue file in Webpack

When I execute webpack watch in the VS2017 task runner, it displays the following error: ERROR in ./wwwroot/js/src/App.vue Module build failed: SyntaxError: Unexpected token { at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:373:25) ...

Encountering Build Issue: "NgSemanticModule is not recognized as an NgModule" persists despite inclusion of dependencies and importing into primary module

I have posted my module, component, and package file here. I am attempting to implement a click event with ngif, but I keep encountering an error. The specific error message is "ERROR in NgSemanticModule is not an NgModule". I'm unsure if this error ...