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

Ignoring TypeScript type errors in ts-jest is possible

Recently, I embarked on a journey to learn TypeScript and decided to test my skills by creating a simple app with jest unit testing (using ts-jest): Here is the code snippet for the 'simple app.ts' module: function greet(person: string): string ...

How can you modify a hyperlink URL before it is activated?

I'm facing an issue with a URL structure that needs updating before it is clicked. The current URL looks like this: https://url.com/a b c which is causing redirection problems because the actual link has underscores instead of spaces in its URL. Is ...

Send users from the web (using JavaScript) to the Windows Phone app, and if the app is not installed, direct them

In the following code snippet, I am using angular.js to detect the mobile platform and redirect to the native app. If the app is not installed, it will redirect to the market: $scope.isMobile = { Android: function() { return navigator.userAgent.ma ...

There is an issue with the Svelte TypeScript error related to the $: syntax, specifically stating that a declaration cannot be used in a

I encountered an issue where I am receiving the error message "Cannot use a declaration in a single-statement context" while using $: syntax in a script with lang="ts" within my +page.svelte file. Additionally, when I check the version control system (VCS) ...

What causes the order of `on` handler calls to be unpredictable in Angular?

Below is the code snippet I have been working on function linkFunc(scope, element, attr){ var clickedElsewhere = false; $document.on('click', function(){ clickedElsewhere = false; console.log('i ...

Is there a way for me to indicate to my custom component the specific location within an input message where a value should be displayed

I'm currently developing a value selector component in ionic/angular and I've encountered an issue with the message/title that I want to pass to the component. I want to be able to specify where the selected value should appear within the message ...

Typescript is being lenient with incorrect use of generics, contrary to my expectations of error being thrown

Encountered a puzzling Typescript behavior that has left me confused. Take a look at the following code snippet: interface ComponentProps<T> { oldObject: T } function Component<T>({ oldObject }: ComponentProps<T>) { const newObject = ...

Learn how to pass JSON data into an anchor tag with Angular router link and the query parameters attribute set as "<a ... [queryParams]="q=|JSON|

As an Angular user, I am trying to populate a query parameter with a JSON object. <ngx-datatable-column name="Sku" prop="product.sku" [flexGrow]="0.5"> <ng-template let-row="row" let-value="value" ...

Exploring the contrasts between one-way binding and two-way binding within AngularJS

Can you please elaborate on the distinction between One-way Data Binding and Two-way Data Binding, providing an example of each and explaining when we would use them? ...

Having constant problems with ngModel twoway binding. Any suggestions on how to successfully bind to a property in order to update an api link?

I am attempting to implement two-way binding in order to dynamically change the API endpoint when a button is clicked. The value attribute of the button should be used as part of the API URL string. I tried following an example in the Hero Angular App, bu ...

Troubleshooting Issue with Chrome/chromium/Selenium Integration

Encountered an issue while attempting to build and start the application using "yarn start": ERROR:process_singleton_win.cc(465) Lock file cannot be created! Error code: 3 Discovered this error while working on a cloned electron project on a Windows x64 m ...

Struggling to connect HTML elements with AngularJS and TinyMCE?

My objective is to edit text using tinymce, persist it in a database, and display it within a div by incorporating angularJS for the same styling and formatting. I am utilizing tinymce 3.5.8 with an angularUI directive. I have successfully saved the wysiw ...

Automatically executing JavaScript function on an AngularJS webpage

Within my AngularJS webpage, I have implemented a self-invoking function. One crucial aspect of this function is the getData() method, responsible for making Ajax calls to fetch data upon page load and user interactions. <script type="text/javascript"& ...

Concerns with displaying elements in Angular JS

As I delve into the world of Angular JS, I'm incorporating it into a game project I've been working on for educational purposes. Surprisingly, my code functions perfectly fine without utilizing ng-show. Things run smoothly with ng-show="true" and ...

Sharing controller methods in Angular.js is a key aspect of enhancing

In my current project, I originally used Knockout for the CMS functionality, but decided to switch to Angular because I preferred its features. One of the key sections in the CMS is dedicated to 'Users', featuring a table where headers can be cli ...

What is the best way to retrieve the rendered content through the `link` function of a directive?

Here is the code snippet below: <div class="test">{{name}}</div> This Angular code demonstrates how to alert the rendered string World: var app = angular.module('angularjs-starter', []); app.controller('MainCtrl', functi ...

substituting the deep watcher in Angular

In my application, I am working with a data object called fulldata, which consists of an array of objects. fulldata = [ {'key': 'abc', values: {.....},....}, {'key': 'efg', values: ...

Is it better to use AngularJS' ngMock inject before each test or for each individual test case?

Current Situation As I work on writing tests for an Angular project, I have come across a common practice of creating "global" variables in a describe block to store dependencies needed for the tests. This approach involves defining variables like $contro ...

Leverage the Power of Two AngularJS Factories

Can I efficiently use two Factories in AngularJS by calling one from the other? Here's the Scenario: I have a Factory that returns an Array. This Factory is responsible for checking if the data to populate this Array already exists in local SQL Stor ...

The provider named toasterProvider is not recognized within the dependency injection chain, which includes toaster, RugHttpInterceptor, $http, and ng1UIRouter

Working with Interceptors to show a toast message when my app encounters an HTTP error in responseError code. Using AngularJS Interceptor for an MEAN.JS app. Interceptor Code angular.module('rugCoPro') .factory('RugHttpInterceptor', ...