Utilizing discriminated unions in conjunction with classes: A step-by-step guide

I'm having an issue converting a discriminated union into a string. The union comprises two interfaces. When I use the function with a simple object that matches one of the interfaces, I get the desired output. However, if I use a class that implements the interface, I receive `undefined`. Can someone clarify this behavior for me? Is there a workaround?

interface Foo {
    kind: 'pending',
    myVar: string
}

interface Bar {
    kind: 'running',
    myVar2: string
}

type FooBarUnion = Foo|Bar;

class FooClass implements Foo {
    kind: 'pending'
    myVar: string

    constructor(text) {
        this.myVar = text;
    }
}

function fbuToString(o: FooBarUnion ) {
    switch (o.kind) {
        case "pending": return `Object is pending. ${o.myVar}`;
        case "running": return `Object is running. ${o.myVar2}`;
    }
}

// prints undefined
console.log(fbuToString(new FooClass('test')));

// prints expected result
console.log(fbuToString({kind:'pending', myVar: 'test'}));

I'm executing this file using ts-node filename.ts

Answer №1

In the code snippet provided, the class 'FooClass' is declared with a property named 'kind' but without assigning it any value initially.

class FooClass implements Foo {
    kind = 'pending' as const
    myVar: string

    constructor(text:string) {
        this.myVar = text;
    }
}

Playground 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

404 Error: Unable to Locate Socket Io

I'm currently working on implementing a chat feature in Angular 2 using Socket IO, following this tutorial. However, I encountered an error message during a test on the server: GET http://localhost:3000/socket.io/?EIO=3&transport=polling& ...

I'm on the lookout for a component similar to angular-ui-tree that is compatible with angular

As a new developer, I am in search of a component similar to: But specifically for Angular 6, with all the same functionality (drag-and-drop capability, nested items, JSON structure, etc.). I have come across some components that either lack dragging fun ...

Utilizing TypeScript to access global variables and external libraries

Currently, I am in the process of converting traditional JavaScript files into TypeScript for use in client-side deployments within SharePoint. Within SharePoint, there are global variables and libraries that we rely on without needing to explicitly load t ...

What is the best way to eliminate hover diagnostic content in my VS Code extension?

I've implemented a VS Code extension where I've added a command to delete a diagnostic: extension.ts context.subscriptions.push( vscode.commands.registerCommand( DELETE_DIAGNOSTIC_COMMAND, () => removeDiagnostic() ) ) ...

Webpack 4 combines the power of Vue with the versatility of Typescript classes and JavaScript code simultaneously

Currently, I am in the process of migrating JS files to Typescript with the objective of being able to utilize both JS and Typescript classes within Vue. While I understand that I can convert Vue scripts into Typescript, I prefer not to do so at this momen ...

I'm having trouble resolving this issue with an Unexpected Application Error! It seems that I cannot set the property value of #<TextFieldBase2> since it only has a

Currently, I'm utilizing TypeScript, React Hook Form, Yup validation, and Fluent UI. Every time I attempt to submit a form, I encounter the error 'Unexpected Application Error! Cannot set property value of # which has only a getter'. https:/ ...

Jackson is unable to deserialize an empty array

Currently, I am analyzing the Facebook Insights data and attempting to map the JSON to an Object named Jackson. I have successfully handled scenarios where all the data is present, but I am facing an issue when trying to deserialize an empty array of key-v ...

Tips for assigning types from an interface object in TypeScript

Here is the code snippet I'm dealing with interface deviceInfo { Data: { model: string; year: number; }; } const gadget: deviceInfo.Data; I encountered a warning in vscode that indicates there ...

The TypeScript import statement is causing a conflict with the local declaration of 'Snackbar'

I'm having trouble using the Snackbar component from Material UI in my React app that is written in TypeScript. Whenever I try to import the component, I encounter an error message saying: Import declaration conflicts with local declaration of &apos ...

Troubles encountered with ionic's usage of [innerHTML] within <ion-list>

Encountering an issue while using ionic 3 and angular 2 with styling a large HTML string using [innerHTML]. Strangely, the string gets cut off at the end of the screen instead of wrapping to the next line when placed within an ion-list tag. Any insights on ...

Following the execution of the commit, the variable remains in a state of

I'm currently in the process of creating a new task. I was expecting the result to be 'created task with title', but the title is empty because 'formData' is still reactive. Below is an example of the code: // index.vue <form ...

the "then" function is causing issues in my TypeScript Node code

My code looks like this: var fs = require('fs'); var util = require('util'); var files = fs.readdirSync('*/path to my folder that contains subfolders*/') async function getfilenum(){ var files_v_num = [] for(const i in fi ...

"Jesting with JavaScript: Thou shall be warned, for undefined does

While running my unit tests with jest, I encountered an error: TypeError: Cannot read properties of undefined (reading 'getVideoTracks') Can anyone provide suggestions on how to properly test the following line using jest? [videoTrack] = (await ...

Tips for continuously running a loop function until retrieving a value from an API within a cypress project

Need help looping a function to retrieve the value from an API in my Cypress project. The goal is to call the API multiple times until we receive the desired value. let otpValue = ''; const loopFunc = () => { cy.request({ method: &ap ...

Using System.import in my code is triggering a cascade of errors in my console

I incorporate the System module in my component. export class LoginComponent { constructor() { System.import('app/login/login.js'); } } The file loads successfully, however, TypeScript compiler raises an error Error:(10, 9) TS2 ...

Is it possible to invoke a function exclusively on the center item within an ngx-owl-carousel?

Is there a way to call a function only when an element is in the center of a slider? This is my HTML: <owl-carousel-o [options]="customOptions"> <ng-container *ngFor="let slide of slides"> <ng-template carous ...

Is it possible to implement a different termination condition when using *ngFor in Angular 2?

After countless hours of searching on Google, I have yet to discover a method for implementing an alternative stop condition for loops created with the *ngFor directive. By default, *ngFor loops end with this condition: index < array.length. Is there a ...

Setting TypeScript versions in Visual Studio Code goes unnoticed

I'm having trouble updating the version of TypeScript that Visual Studio Code is running. After carefully reading through the response to this question, I attempted to modify my user settings using: { "typescript.tsdk": "C:\\Users&bso ...

Analyzing memory consumption by an individual function in a Node.js environment

Our current experiment involves measuring the memory usage of specific functions. Initially, we attempted to utilize process.memoryUsage().heapUsed before and after calling the function, but encountered issues due to the behavior of the garbage collector. ...

An issue has occurred: function() is not a valid function

Issue: core.mjs:10132 ERROR TypeError: block.getDepartment is not a function at FirebaseService.mapDatabaseToBlock (firebase.service.ts:54:30) at firebase.service.ts:45:60 at Array.map (<anonymous>) at firebase.service.ts:45:42 at ...