Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TypeScript] Class Visitor defines instance member property visit, but extended class defines it as instance member function. #4721

Open
tpluscode opened this issue Oct 24, 2024 · 3 comments

Comments

@tpluscode
Copy link

tpluscode commented Oct 24, 2024

The TypeScript target produces a visitor similar to the following:

export default class FooVisitor<Result> extends ParseTreeVisitor<Result> {
	/**
	 * Visit a parse tree produced by `FooParser.bar`.
	 * @param ctx the parse tree
	 * @return the visitor result
	 */
	visitBar?: (ctx: BarContext) => Result;
}

When overridden as shown in the docs, the code doesn't work (override is never called) and the compiler will show an error explaining the reason:

TS2425: Class FooVisitor defines instance member property visitBar, but extended class CustomVisitor defines it as instance member function.

As a workaround, it is possible to switch to a property:

class CustomVisitor extends FooVisitor<X> {
  visitBar = (ctx: BarContext): X => {
    return new X()
  }
}

but I expect that the intent from the target is overloading, same as one would overload the visitor methods in plain JS target. To allow that, the target can be modified to

-export default class FooVisitor<Result> extends ParseTreeVisitor<Result> {
+export default abstract class FooVisitor<Result> extends ParseTreeVisitor<Result> {
	/**
	 * Visit a parse tree produced by `FooParser.bar`.
	 * @param ctx the parse tree
	 * @return the visitor result
	 */
-	visitBar?: (ctx: BarContext) => Result;
+	visitBar?(ctx: BarContext) => Result;
}
@tpluscode tpluscode changed the title [TypeScript] [TypeScript] Class Visitor defines instance member property visit, but extended class defines it as instance member function. Oct 24, 2024
@ericvergnaud
Copy link
Contributor

Hi, thanks for this. Can you provide a pointer to the docs you are referring to?

@tpluscode
Copy link
Author

For reference, here's an SO question which links to relevant TypeScript docs: https://stackoverflow.com/questions/44153378/typescript-abstract-optional-method

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants
@tpluscode @ericvergnaud and others