Open git-denial opened 1 year ago
I try it in ts playground. Get a lot of errors.Could u check this code?
Actually I run the AST parser in a javascript file. Here is a simpler version of the code:
const acorn = require("acorn")
const tsPlugin = require("acorn-typescript")
let source = `
import {NextFunction, Request, Response} from "express";
import {
BadParamIdError,
BadRequestError,
EntityNotFoundError,
InternalServerError,
UnauthorizedError
} from "../errors/RequestErrorCollection";
export async function getById(req: Request, res: Response, next: NextFunction) {
try {
let id = parseInt(<string>req.params.id)
if (isNaN(id)) return next(new BadParamIdError)
return res.send(id)
} catch (e) {
next(new InternalServerError(e))
}
}
`
let node = acorn.Parser.extend(tsPlugin.tsPlugin({dts:false})).parse(source, { sourceType: 'module', ecmaVersion: 'latest', locations: true })
console.log(node)
The point is, the error occurs whenever there is any type assertion in the code be it : <number>
, <string>
, <boolean>
, etc...
This is a very ambiguous syntax between JSX and TS. You can see in the stack trace that it's being treated as JSX. We could expect independent parsers to accomdate the growing complexity created by these heterogenous semiotics, but i think it would be even preferrable to favor a simpler syntax of type casting (process.env.TOKEN_SECRET as Secret) in this case when its possible if you have means to edit. not just me saying it: https://stackoverflow.com/questions/49818305/what-are-the-difference-between-these-type-assertion-or-casting-methods-in-types "there is an ambiguity in the language grammar when using <> style assertions in JSX, hence recommended to use 'as' for consistency"
This is a very ambiguous syntax between JSX and TS. You can see in the stack trace that it's being treated as JSX. We could expect independent parsers to accomdate the growing complexity created by these heterogenous semiotics, but i think it would be even preferrable to favor a simpler syntax of type casting (process.env.TOKEN_SECRET as Secret) in this case when its possible if you have means to edit. not just me saying it: https://stackoverflow.com/questions/49818305/what-are-the-difference-between-these-type-assertion-or-casting-methods-in-types "there is an ambiguity in the language grammar when using <> style assertions in JSX, hence recommended to use 'as' for consistency"
I haven't tried the type casting approach but that seems to be a valid temporary solution. However, changing all of the type assertion to type casting would seems to be a pretty tedious work in a large codebase. I don't really need the type assertion in the return response for now, so my temporary solution for now is to delete the type assertion before being parsed by the AST parser.
This is the parser code that I used
The source code file contains the Secret type assertion which cause the parser to fail:
Error:
Are there some additional options that I need to enable to make this work ?