Issue with TypeScript function overloading: Visitor Pattern not working as expected

I've been working on implementing a Visitor Design pattern, but I keep running into a compilation error that I just can't seem to resolve no matter how many hours I spend trying to find a solution...

Here's my Visitor interface:

export interface Visitor {
    visit(a: A): X;
    visit(b: B): Y;
}

And here's my Visitor implementation:

export class VisitorImp implements Visitor {

    visit(a: A): X {
        return a.getX();
    }

    visit(b: B): Y {
        return b.getY();
    }
}

Unfortunately, I'm encountering the following compilation error:

Property 'visit' in type 'VisitorImp' is not assignable to the same property in base type 'Visitor'.
  Type '(a: A) => X' is not assignable to type '{ (a: A): X; (b: B): Y; }'.
    Type 'X' is missing the following properties from type Y

I'm really hoping someone can assist me with this issue because it's starting to drive me crazy!

Answer №1

I haven't actually tried this out, but you might want to consider experimenting with the following code:

export interface Visitor {
    visit: ((a: A) => X) | ((b: B) => Y);
}

I came across this snippet while browsing this website.

UPDATE:

Upon further examination, it seems that the initial implementation might not be very elegant. In that case, you can try this alternative:

interface Visitor {
    visit(a: String): Number;
    visit(b: Number): String;
}

class VisitorImp implements Visitor {

    visit(a: String): Number;
    visit(b: Number): String;
    visit(a: String | Number): Number | String {
        if(a instanceof String) {
            return 0;
        } else {
            return "";
        }
    }
}

Here, String/Number represent A/B. More details can be found here.

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

Is there a way for me to showcase a particular PDF file from an S3 bucket using a custom URL that corresponds to the object's name

Currently, I have a collection of PDFs stored on S3 and am in the process of developing an app that requires me to display these PDFs based on their object names. For instance, there is a PDF named "photosynthesis 1.pdf" located in the biology/ folder, and ...

Adding items to the array is only effective when done within the loop

My approach involves retrieving data from an API using axios, organizing it within a function named "RefractorData()," and then pushing it onto an existing array. However, I have encountered a problem where the array gets populated within a forEach loop, a ...

I am looking for a way to transfer data collected from an input form directly to my email address without the need to open a new window. As of now, I am utilizing angular

Is there a way to send this data to my email address? I need help implementing a method to achieve this. {Name: "John", phoneNumber: "12364597"} Name: "John" phoneNumber: "12364597" __proto__: Object ...

When I delete the initial element from the array, the thumbnail image disappears

Using react-dropzone, I am attempting to implement image drag and drop functionality. The dropped image is stored in the React state within a files array. However, a problem arises when removing an image from the array causing the thumbnails of the remain ...

Typescript counterpart of a collection of key-value pairs with string keys and string values

Within the API I'm currently working with, the response utilizes a data type of List<KeyValuePair<string, string>> in C#. The structure appears as shown below: "MetaData": [ { "key": "Name", &q ...

Utilizing Angular CDK to link several drop zones together using the cdkDropListConnectedTo directive

Currently in the process of designing a basic board interface with swim lanes similar to Jira swimlane or trello boards https://i.sstatic.net/7MBvm.png The red lines indicate the current flow The blue lines represent the flow that I aim to implement The ...

The problem arises when the type of a Typescript literal union becomes more specific within React children

Currently, I am in the process of converting our React/Redux project to TypeScript and encountering a challenge with TypeScript literal type union types. The issue that I'm facing is as follows: I have instantiated a Wrapper component with a type pr ...

What is the process for creating static pages that can access local data within a NextJS 13 application?

I recently completed a blog tutorial and I must say, it works like a charm. It's able to generate dynamic pages from .md blog posts stored locally, creating a beautiful output. However, I've hit a roadblock while attempting what seems like a sim ...

The incorrect initial state is causing issues in the Zustand state management on the Next.js server side

While utilizing zustand as a global state manager, I encountered an issue where the persisted states were not being logged correctly in the server side of nextjs pages. The log would only show the default values (which are null) and not the updated state v ...

Accessing the 'comment' property within the .then() function is not possible if it is undefined

Why does obj[i] become undefined inside the .then() function? obj = [{'id': 1, 'name': 'john', 'age': '22', 'group': 'grA'}, {'id': 2, 'name': 'mike', &apo ...

Tips for presenting a quiz in a random order and preventing duplicate questions in a React Native app

Hello everyone, I am working on creating a Quiz app in React Native that displays questions randomly without any duplication. So far, I have managed to display the Quiz questions randomly, but I'm stuck on preventing duplicates. This is a new learning ...

Associate the generic operator <T> with a FunctionConstructor

In my TS function, I deserialize JSON into a specific type/object by providing it with a constructor function of that type which reconstructs the object from JSON. Here is how it looks like: export function deserializeJSON<T>(JSONString: string, ty ...

Upon executing the tsd install and tsd query commands, a message indicating 'no results found' was displayed

Whenever I run these commands in Git Bash on Windows tsd query angular-material tsd query angular tsd install angular angular-material I always receive the message ">> zero results" ...

Typescript typings for child model/collection structures

I have encountered an issue while trying to implement a Model/Collection pattern with various typings. Both the Model and Collection classes have a method called serialize(). When this method is called on the Collection, it serializes all the Model(s) with ...

"Transferring a C# dictionary into a TypeScript Map: A step-by-step

What is the correct way to pass a C# dictionary into a TypeScript Map? [HttpGet("reportsUsage")] public IActionResult GetReportsUsage() { //var reportsUsage = _statService.GetReportsUsage(); IDictionary<int, int> te ...

What is the process for incorporating the jsnetworkx library into an ionic or angular 4 project?

When using any Ionic3 app service import * as jsnx from 'jsnetworkx'; The output error message is: Uncaught (in promise): Error: Cannot find module "lodash/lang/isPlainObject" Error: Cannot find module "lodash/lang/isPlainObject" at webpackMis ...

Accessing Angular's Observable Objects

I am currently in the process of learning Angular and trying to work with Observables. However, I am facing an issue where I cannot extract data from an Observable when it is in object form. public rowData$!: Observable<any[]>; UpdateGrid() { this ...

How can I extract a value from an object that is readonly, using a formatted string as the key?

I encountered a situation where I have code resembling the following snippet. It involves an object called errorMessages and multiple fields. Each field corresponds to various error messages in the errorMessages object, but using a formatted string to retr ...

Is it possible to assign an interface to an object property in TypeScript?

I am currently working with an object that looks like this: export class Section{ singleLabel:string; pluralLabel:string; index:number; dataInterface:Interface; } My goal is to assign an interface to the dataInterface field, as I need to use the S ...

Can anyone provide guidance on creating a new type in Ionic Vue?

How can I define the description as a type in my code? When I run it, I get an error that says "Property 'description' does not exist on type '{ takePhoto(): Promise; }'" <script lang="ts"> import { IonPage, ...