z-pattern-matching / z

Pattern Matching for Javascript
https://z-pattern-matching.github.io/
Apache License 2.0
1.72k stars 50 forks source link

does not work with typescript #35

Open bhavinkamani opened 7 years ago

bhavinkamani commented 7 years ago

Strange but when I use some of the snippets with typescript, it always returns the result of the first param. For example

import {matches} from 'z';

const person = { name: 'Maria' }
matches(person)(
  (x = { name: 'John' }) => console.log('John you are not welcome!'),
  (x)                    => console.log(`Hey ${x.name}, you are welcome!`)
)

returns John you are not welcome.

mindreframer commented 7 years ago

this is what typescript compiles down to:

$ mkdir ztypescripttest && cd ztypescripttest
$ yarn init -y 
$ yarn add z typescript 
$ vim index.ts # paste the example from above
$ ./node_modules/.bin/tsc index.ts
$ cat index.js
"use strict";
exports.__esModule = true;
var z_1 = require("z");
var person = { name: 'Maria' };
z_1.matches(person)(function (x) {
    if (x === void 0) { x = { name: 'John' }; }
    return console.log('John you are not welcome!');
}, function (x) { return console.log("Hey " + x.name + ", you are welcome!"); });
rnsell commented 6 years ago

Z uses a module to get meta data about functions, specifically information about default params. It then uses the reflection meta data to choose which function to run. If any code is transpiled to es5 the es6 code default assignements are removed from the function signature thus resulting in broken code. The above code needs to transpile to es6 or higher to work properly. This probably also means z pattern matching will break on babel transpiled code to es5.

alfredosalzillo commented 5 years ago

Hi, i release a babel plugin to preserve the toString of transpiled arrow function, i tested in a project with z and it seems work babel-plugin-preserve-arrow-function-to-string.