Recently, I came across a discussion suggesting that Nashorn in JDK 9 should have the capability to parse TypeScript. Excited to try it out, I attempted to use it like this:
Parser parser = Parser.create();
CompilationUnitTree tree = parser.parse(file, new InputStreamReader(stream), null);
Testing it on examples from https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html, the plain JavaScript code worked fine. But when I tried the example with a type declaration, it threw an error:
jdk.nashorn.internal.runtime.ParserException: a.ts:1:23 Expected , but found :
function greeter(person:string) {
^
at jdk.scripting.nashorn/jdk.nashorn.internal.parser.AbstractParser.error(AbstractParser.java:297)
at jdk.scripting.nashorn/jdk.nashorn.internal.parser.AbstractParser.error(AbstractParser.java:282)
at jdk.scripting.nashorn/jdk.nashorn.internal.parser.AbstractParser.expectDontAdvance(AbstractParser.java:353)
at jdk.scripting.nashorn/jdk.nashorn.internal.parser.AbstractParser.expect(AbstractParser.java:340)
at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Parser.formalParameterList(Parser.java:3991)
at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Parser.formalParameterList(Parser.java:3966)
at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Parser.functionExpression(Parser.java:3802)
at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Parser.statement(Parser.java:1099)
at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Parser.sourceElements(Parser.java:909)
at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Parser.program(Parser.java:844)
at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Parser.parse(Parser.java:325)
at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Parser.parse(Parser.java:285)
at jdk.scripting.nashorn/jdk.nashorn.api.tree.ParserImpl.parse(ParserImpl.java:117)
at Main.process(Main.java:299)
at Main.main(Main.java:113)
The error message clearly indicates that the parser is not familiar with TypeScript and does not have support for it. There seems to be no parameter available to specify the language variant.
Am I missing something here? Is there a workaround to make this work?