ts-expressions [WORK IN PROGRESS]
A TypeScript transformer to convert TypeScript expressions into equivalent expression trees
Description
ts-expressions
is a TypeScript transformer that helps you get information about an expression at run-time by creating an object structure representing that expression at compile-time.
How to install
npm i ts-expressions
How does it work
The transformer provided by ts-expressions
will analyze TypeScript code and look for calls to functions that contain an overload which declares parameters of type Expression
. If the function call being analyzed is passing arguments of types other than Expression
, those arguments are converted to expressions during the compilation of the program.
You will need to use a custom TypeScript compiler to make use of the ts-expressions
transformer. You can use ttypescript to compile your program using the following configuration in ts.config
:
If you're feeling adventurous you can also create your own TypeScript compiler:
;; ;;; ;
It is currently not supported to use the out-of-the-box TypeScript compiler tsc
with this plug-in. You can show some love here if you'd like to see plugin support built into the TypeScript compiler.
How to use
To declare a function that accepts expressions, you must declare one signature overload that uses parameters of type Expression<T>
and another equivalent overload signature that uses parameters of type T
which will be used by callers. ts-expressions
will only convert supported expressions.
For example, to work with numeric expressions, you could write the following function:
; ;;
Then call it using:
numeric5 + 1;
Which would be translated by the transformer to:
; numericbuilder.createExpression builder.binary builder.constant5, BinaryOperator.plus, builder.constant1;
Note that ts-expressions
will only match overload signatures with the same number of parameters and where parameters have compatible expression types.
The following examples work:
;; ;; ;;
The following examples will not work:
;; ;; ;;