Awesome
<!--@[h1([pkg.name]), paragraph([pkg.description])]-->typescript-transform-macros
Typescript Transform Macros
<!--/@--> <!--@shields("npm", "prettier", "ConventionalCommits", "spacemacs")--> <!--/@-->Examples from https://github.com/codemix/babel-plugin-macros.
<!--@installation()-->Installation
npm install --save-dev typescript-transform-macros
<!--/@-->
Usage with ttypescript
Add it to plugins in your tsconfig.json
{
"compilerOptions": {
"plugins": [{ "transform": "typescript-transform-macros" }]
}
}
Also declare globally the MACRO function:
declare function MACRO<T>(t: T): T;
Example
Input:
<!--@snippet("./examples/ttypescript/index.ts")-->declare function MACRO<T>(t: T): T;
const MAP = MACRO(
<T, L>(
inputConst: T[],
visitor: (value: T, index?: number, input?: T[]) => L
) => {
const input = inputConst;
const length = input.length;
const result = new Array(length) as L[];
for (let i = 0; i < length; i++) {
result[i] = visitor(input[i], i, input);
}
return result;
}
);
declare interface Array<T> {
MAP: Array<T>["map"];
}
console.log([1, 2, 3].MAP(n => 3 * n + 1));
<!--/@-->
Output:
<!--@example("./examples/ttypescript/index.js")-->"use strict";
const input_1 = [1, 2, 3];
const length_1 = input_1.length;
const result_1 = new Array(length_1);
for (let i_1 = 0; i_1 < length_1; i_1++) {
result_1[i_1] = 3 * input_1[i_1] + 1;
}
console.log(result_1);
//> [ 4, 7, 10 ]
<!--/@-->