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

`only` option doesn't skip files that have no leading comments #160

Closed lshearer closed 7 years ago

lshearer commented 8 years ago

When using the only option to opt files in to type checking, files that have no leading comments will not be skipped. This can result in runtime errors.

E.g., given the following files: index.js

import doSomething from './doSomething';

doSomething('hey');

doSomething.js (has no leading comments)

import type {MyType} from './MyType';

export default function(myType: MyType){
  console.log(myType);
};

MyType.js

// @flow
// This file has leading comments
export type MyType = any;

and a .babelrc with a plugin section including:

    [
      "typecheck",
      {
        "only": [
          "production",
          "test"
        ]
      }
    ]

When running the transpiled index.js file, you'll encounter an error like TypeError: MyType is not a function. This is because doSomething.js was processed for type checking and resulted in something semantically similar to

import {MyType} from './MyType';

export default function(myType: MyType){
  if (!MyType(myType)) {
    throw new TypeError('Value of argument...');
  }
  console.log(myType);
};

but MyType.js was not processed for type checking, so it resulted in something like

"use strict";

This results in a failed validation call because the imported MyType is undefined, whereas it would be a validation method had it been processed as well.

The problem appears to be that one of the checks to enforce the only option is skipped if the file doesn't have any leading comments, resulting in that file getting processed, even though it does not contain a // @typecheck production (or similar) pragma.

Although files with flow types are likely to contain at least a // @flow leading comment, this is not required and is still a valid case which can lead to very confusing errors.

phpnode commented 7 years ago

Hi sorry for the delay, this project is now deprecated in favour of flow-runtime which aims for full flow compatibility. flow-runtime has a slightly different method of specifying pragmas, see here - https://codemix.github.io/flow-runtime/#/docs/pragmas