Skip to content

LeDDGroup/typescript-transform-macros

Repository files navigation

typescript-transform-macros

Typescript Transform Macros

Build Status Maintainability codecov

npm version code style: prettier Conventional Commits Built with Spacemacs

Examples from https://github.com/codemix/babel-plugin-macros.

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:

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:

"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 ]