codemix / babel-plugin-typecheck

Static and runtime type checking for JavaScript in the form of a Babel plugin.
MIT License
886 stars 44 forks source link

Support for destructured variables? #13

Closed mistadikay closed 9 years ago

mistadikay commented 9 years ago

Hi,

What are the thoughts/plans about supporting destructured variables, like this:

function({ state: string, id: number }) {
    // ...
}

Thanks

phpnode commented 9 years ago

Those aren't type annotations, that syntax aliases arguments[0].state to string and arguments[0].id to number: https://babeljs.io/repl/#?experimental=true&evaluate=true&loose=false&spec=false&playground=true&code=function%20abc%20(%7B%20state%3A%20string%2C%20id%3A%20number%20%7D)%20%7B%0A%20%20%20%20%2F%2F%20...%0A%7D

mistadikay commented 9 years ago

@phpnode you're right, my bad I didn't know about these aliases. But could you answer my question please? Any thoughts/plans of supporting destructured variables? Let's say we have something like this:

function({ state, id }) {
    // ...
}
phpnode commented 9 years ago

Sorry, I closed this a bit hastily. It's sort of supported at the moment, e.g. this works:

function a ({k, v}: {k: string, v: string}) {
  return [k, v];
}

but the code it generates is really terrible. I'll fix this.

mistadikay commented 9 years ago

@phpnode got it, thank you!

elado commented 9 years ago

Fails with default values on keys:

function fn({ d='default' }: {d: string}) {
  console.log(d);
}

console.log(fn({ d: 'value'}));

Compiles to

    if ({ d = 'default' } === null || typeof { d = 'default' } !== 'object' || typeof { d = 'default' }.d !== 'string') throw new TypeError('Value of argument \'undefined\' violates contract, expected Object with a d property got ' + ({ d = 'default' } === null ? 'null' : { d = 'default' } instanceof Object && { d = 'default' }.constructor ? { d = 'default' }.constructor.name : typeof { d = 'default' }));
            ^

SyntaxError: Unexpected token =