An issue arising with the TypeScript antlr4ts listener type

I am currently attempting to incorporate the antlr4 parser into an angular project.

Within a dataservice class, there is a function being called that appears as follows:

parseRule() {
  const ruleString = ' STRING TO PARSE';

  const inputStream = new ANTLRInputStream(ruleString);
  const lexObject = new lexer.scopeLexer(inputStream);
  const tokenStream = new CommonTokenStream(lexObject);
  const parseObject = new parser.scopeParser(tokenStream);
  const result = parseObject.file();
  const evaluator = new ScopeEvaluator();
  const walker = new ParseTreeWalker();

  walker.walk(evaluator, result);
  console.log('result:', result.text);
}

A customer listener is implementing the interface, exported with just one method - enterNonGraphScope.

import { scopeListener } from './antlrscope/scopeListener';
import { NonGraphScopeContext, NamesetSimpleContext } from './antlrscope/scopeParser';

export class ScopeEvaluator implements scopeListener {

  constructor() {
    console.log('constructed the asdfasf');
  }

  enterNonGraphScope = function (ctx: NonGraphScopeContext) {
    console.log('Tis', ctx.text);
  };

}

Included below is an excerpt from the scopeListener.ts file for clarifying the interface:

export interface scopeListener extends ParseTreeListener {

/**
 * Enter a parse tree produced by the `NonGraphScope` labeled alternative in `scopeParser.scope`.
 * @param ctx the parse tree
*/
enterNonGraphScope?: (ctx: NonGraphScopeContext) => void;

While running the Angular's ng serve command (which compiles TypeScript code), I encounter the following error:

ERROR in src/app/rule-parser.service.ts(31,17): error TS2559: Type 'ScopeEvaluator' has no properties in common with type 'ParseTreeListener'.

Displayed below is the listener generated in TypeScript. (Excluding contents and comments generated by Antlr)

export interface scopeListener extends ParseTreeListener {
    ...
}

It seems like there might be some issues related to the interpretation or typing of TypeScript. As I am relatively new to JavaScript/TypeScript, any assistance would be greatly appreciated.

The webpack/generated JavaScript code works without any problems, but this particular error stands in the way of successfully generating the build.

Thank you!

-Vinayak

Answer №1

After conducting some research, I discovered that the issue is related to changes in weak type handling. For more detailed information, you can check out the following link:

I also came across a related discussion on Stack Overflow at After upgrading TypeScript, Angular controller registration now fails to compile

The following modifications to the class implementing interfaces proved effective. Option 1, which involves a type assertion, appears to be the preferable choice.

Option 1

    parseRule() {
      const ruleString = ' Scope: (Dim1.Attr1 * &Namset1);' +
        ' Measure.[asdfa] = ddd ;' +
        'end scOPe;';

      const inputStream = new ANTLRInputStream(ruleString);
      const lexObject = new lexer.scopeLexer(inputStream);
      const tokenStream = new CommonTokenStream(lexObject);
      const parseObject = new parser.scopeParser(tokenStream);
      const result = parseObject.file();
      const evaluator = new ScopeEvaluator();
      const walker = new ParseTreeWalker();
      console.log(' type of ' , evaluator);
      walker.walk(evaluator as ParseTreeListener, result);
        // Parse and execute the code.
        console.log(' p :', parseObject);
      console.log(' result :', result.text);
    }

Option 2 - involves redeclaring stuff ?

            import { scopeListener } from './antlrscope/scopeListener';
            import { NonGraphScopeContext, NamesetSimpleContext } from './antlrscope/scopeParser';
            import { ParseTreeListener } from 'antlr4ts/tree/ParseTreeListener';


            export class ScopeEvaluator implements scopeListener {

                visitTerminal = () => { };
                visitErrorNode = () => { };
                enterEveryRule = () => { };
                exitEveryRule = () => { };
                enterNonGraphScope = function (ctx: NonGraphScopeContext) {
                    console.log('Tis ', ctx.text);
                };
            }

If you believe there is a better approach to solving this problem, please provide your feedback. My grasp of TypeScript may not be comprehensive enough to consider all possibilities.

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

How can I arrange the ng-class based on the clicked item's order?

http://plnkr.co/edit/pUtuZy?p=preview In this scenario, there are three different border classes available: .border1 { border: 1px solid #66FFFF; } .border2 { border: 1px solid #33CCFF; } .border3 { border: 1px solid #0099FF; } The goal is to as ...

How to get the clean URL in AngularJS without any parameters using $location

One issue I'm facing is related to the URL structure of my application. It currently looks like this: "http://host:port/mySystem?x.system" The addition of x.system in the URL was necessary due to a legacy application requirement, but now I need the U ...

Navigating through the nested object values of an Axios request's response can be achieved in React JS by using the proper

I am attempting to extract the category_name from my project_category object within the Axios response of my project. This is a singular record, so I do not need to map through an array, but rather access the entire object stored in my state. Here is an ex ...

Using Angular's ng-click to navigate to a new page and sending parameters:

Upon clicking the edit button, a new page will be opened and a REST call will be made to populate the page with the parameters passed in. ...

Unable to adjust the text color to white

As someone who is new to Typescript, I'm facing a challenge in changing the text color to white and struggling to find a solution. I'm hoping that someone can guide me in the right direction as I've tried multiple approaches without success ...

Pausing in a NodeJS HTTP request listener until receiving another response before proceeding

Essentially, this is a web proxy. Within a request listener, I am creating another http request, reading its response, and passing it to the main response. But I have the challenge of needing to wait for the secondary request to complete before continuing. ...

Combining AngularJS, D3, and JQuery on a single webpage can pose challenges, specifically with D3's ability to accurately read DOM dimensions

I am encountering an issue with my webpage not loading properly. I have structured it using a simple header-body-footer layout in html5 and CSS3. +----------+ | HEADER | +---+----------+---+ | BODY | +---+----------+---+ | FOOTE ...

Disabling an anchor using the 'disabled' property is proving to be a challenge for me

I'm attempting to dynamically enable or disable an anchor element based on the user's role. So far, I've tried a few different methods: document.getElementById('myBtn').disabled = true; However, this returns an error: The propert ...

Encountering 404 errors when reloading routes on an Angular Azure static web app

After deploying my Angular app on Azure static web app, I encountered an error. Whenever I try to redirect to certain routes, it returns a 404 error. However, if I navigate from one route to another within the app, everything works fine. I have attempted t ...

Is it possible to alter the parent scope from an AngularJS directive?

I am currently in the process of constructing my initial Angular application, but I am encountering some difficulties while attempting to achieve a specific functionality. The issue revolves around a video container which is supposed to remain hidden until ...

An error being thrown within the error function of $http during a unit test is triggering a $digest already in progress

Have a look at this Plunker showcasing the issue: http://plnkr.co/edit/J8zRIj?p=preview If you check out this other Plunker where the error is no longer present in both scripts.js and scripts.spec.js, you'll see that the $digest error is resolved: ...

Error encountered on login page: The protocol 'http' does not exist (related to HTML, TypeScript, Angular2, and JavaScript)

Screenshot of the issue: Access the complete project here: Link to a Plunker example of a log-in screen: http://plnkr.co/edit/j69yu9cSIQRL2GJZFCd1?p=preview (The username and password for this example are both set as "test") Snippet with the error in ...

transmitting error messages from a service to a controller in AngularJS

Controller.js var vm = this; vm.admin = {}; vm.add = function () { API.addAdmin(token, vm.admin) .then(function (resp) { vm.hideForm = true; vm.showButton = true; Notify.green(resp); }, function (re ...

Using a custom TypeScript wrapper for Next.js GetServerSideProps

I developed a wrapper for the SSR function GetServerSideProps to minimize redundancy. However, I am facing challenges in correctly typing it with TypeScript. Here is the wrapper: type WithSessionType = <T extends {}>( callback: GetServerSideProps&l ...

Guide to iterating through an Observable<Object[]> to generate an array of objects

Google Firestore collection named users is structured as follows : { "contactNumber":"0123456789", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88e2e7e0e6ece7edc8efe5e9e1e4a6ebe ...

Reading JSON documents in JavaScript through multiline strings

Having a JSON document with multiline string data is causing issues for me. I have attempted multiple options, but none of them have successfully solved the problem. For example: [ { "someString" : "A rather long string of English text, an error m ...

Initiating communication with a web service API

I am struggling to retrieve data from a web service API and I can't seem to display anything. As a newcomer to AngularJS, I would greatly appreciate any assistance. Below is the controller and factory code that I am currently using: Controller app.c ...

tips for sending types as properties in a versatile component

I am facing a challenge with passing types as props to a reusable component. I have a component where I pass rows and headings as props, but I need to find a way to pass types as props as well. Below is the code for my reusable component: import { TableCe ...

Having multiple Angular two applications running simultaneously within a single webpage

I have encountered an issue while trying to display two separate Calendars on a single page. The first Calendar loads successfully, but the second one does not load at all. There seems to be no attempt made to load it. As I am relatively new to Angular, I ...

Angular 14 captures typed form data as `<any>` instead of the actual data types

On the latest version of Angular (version 14), I'm experiencing issues with strictly typed reactive forms that are not functioning as expected. The form initialization takes place within the ngOnInit using the injected FormBuilder. public form!: For ...