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

WIP: 3.0.0 #43

Closed phpnode closed 9 years ago

phpnode commented 9 years ago

(Don't merge this yet)

This is the work in progress rewrite to become compatible with babel6.

Todo:

Fixes #42 Fixes #39 Fixes #16 Fixes #13 Fixes #10 Fixes #3 Fixes #2

for reference: https://gist.github.com/hzoo/e3a7db9be7a3b0c2094e

Changes

Supports type aliases:

type Foo = string|number;

function demo (input: Foo): string {
  return input + '  world';
}

demo('hello'); // ok
demo(123); // ok
demo(["not", "a", "Foo"]); // fails

Better static type inference

function demo (input: string): Array<string> {
  return makeArray(input); // no return type check required, knows that makeArray is compatible
}

function makeArray (input: string): Array<string> {
  return [input];
}

Type propagation

function demo (input: string): User {
  const user = new User({name: input});
  return user; // No check required, knows that user is the correct type
}

Assignment tracking

let name: string = "bob";

name = "Bob"; // ok
name = makeString(); // ok
name = 123; // SyntaxError, expected string not number

function makeString (): string {
  return "Sally";
}

Type casting

let name: string = "bob";

name = "Bob";
((name: number) = 123);
name = 456;
name = "fish"; // SyntaxError, expected number;

Array type parameters

function demo (input: Array<string>): number {
  return input.length;
}

demo(["a", "b", "c"]); // ok
demo([1, 2, 3]); // TypeError

Shape tracking

type User = {
  name: string;
  email: string;
};

function demo (input: User): string {
  return input.name;
}

demo({}); // TypeError
demo({name: 123, email: "test@test.com"}); // TypeError
demo({name: "test", email: "test@test.com"}); // ok
phpnode commented 9 years ago

@fixplz @motiz88 @STRML this is getting pretty close now, it'd be awesome if you could try it out.

STRML commented 9 years ago

Yeah, will do @phpnode , thanks for the great work!