Typescript Expression Transformer
Expression trees for TypeScript similar to C#. This is the TypeScript transformer plugin.
Expression Type
;
This expression type is declared inside package which you need for runtime. It declares the Expression, ExpressionKind enum (taken from TypeScript) and maybe more runtime features in the future.
Example
An example demonstrating usage of member expression (PropertyAccessExpression
) used to generate HTML Ids for model's elements.
There is function fieldIdFor() which takes Expression argument. In TypeScript you set some arrow function as an argument (eg. m => m.foo).
In transpile time, the transformer looks up all CallExpression
of method/function declaration with parameter of type Expression<>.
Then it takes the argument, creates the expression tree and replace the original expression with object (representing type Expression<>).
Get Started
Create project folder and run npm i typescript-expression-transformer ttypescript -D && npm i js-expr-tree
Source
src/field-id-for.ts
; // the runtime package of this transformer; it's a dependency /** * Construct path from member expression * @param node * @param ignoredProperties * @param path */ /** * Generate html id for model's property member expression * @param memberExpression */
This module exports the fieldIdFor function which returns the HTML id constructed by member expression tree.
Result Usage
Create random ts file with usage of fieldIdFor function.
index.ts
console.log"Generated id for property:", fieldIdForm.baz.deepProp;
Create typescript config file.
tsconfig.json
Using ttypescript
package, you can transpile source by running ttsc
. index.js will be created.
Transpiled Code
index.js
"use strict";Object;var field_id_for_1 = ; console;
Run node index.js
and you'll see the result.
Result
Generated id for property: baz_deepProp
Tip
For work with AST you can use https://astexplorer.net which prints tree nicely. Use the TypeScript AST.