Typescript Compiler - Implement custom transformer

656 Views Asked by At

Iv'e read alot of the Typescript github issues regarding implementation but there's little documentation or people working in this area.

My goal is to basically have typescript understand that..

[1,2,3,4,5].filter(_ % 2).map(_ + 2)
[{name: "test"}, {name: "test2"}].map(_.name).map(_.toUpperCase())

is the same as...

[1,2,3,4,5].filter((x) => x % 2).map((x) => x + 2)
[{name: "test"}, {name: "test2"}].map((x) => x.name).map((x) => x.toUpperCase())

i either want to define a SweetJS macro to convert all underscores to (x) => x at compile time or (peferably) have typescript apply that transformation for me since SweetJS is fairly hacky.

(For reference https://github.com/sweet-js/sweet-core)

How would i go about implementing something that allows typescript to at the bare minimum understand underscore syntax in the correct context \AND\ if possible transform underscores at compile time.

EDIT3: (Edit3 is here for readability) this is how far i have got with the problem, i have opted not to change the compiler to think it is a different type but instead do this....

declare const _: (<T>(arg: T) => T) & { [key: string]: () => any }
const test = [{name: "Shanon", age: 24}].filter(_.age);

which typescript is now happy with, but it is not typesafe so any help would be appreciated.

EDIT: With my minimal compiler skills, i think that i need typescript to understand that when i am within the context of a "CallExpression" underscore has a very unique meaning (CallExpression in the AST).

EDIT2: enter image description here this is the AST defintiion i need outputted (something like this) it's important to note, i don't want the underscore converted before it is typechecked but i want to controle how a underscore is type checked. It should only treat the underscore as this type inside a CallExpression AST type

0

There are 0 best solutions below