Skip to content

Instantly share code, notes, and snippets.

@thomasboyt
Created April 25, 2016 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasboyt/794fe7d81330c4b245d1ff7e38b0508c to your computer and use it in GitHub Desktop.
Save thomasboyt/794fe7d81330c4b245d1ff7e38b0508c to your computer and use it in GitHub Desktop.

basically, in typescript i can do:

interface MyObjectType {
  a: number;
  b?: number;
}

const obj: MyObjectType = {
  a: 1,
  // b is left off
};

console.log(obj.b + 5);  // NaN

and it type-checks just fine. this is because in typescript you have to remember to do != null on anything you access that can be null. meanwhile, in flow:

type MyObjectType = {
    a: number;
    b?: number;
}

const obj: MyObjectType = {
    a: 1,
}

console.log(obj.b * 5);

gives an error: "undefined: This type is incompatible with number." basically, it's saying "well, b can be undefined, but there's no way you'd want to use an undefined reference with arithmetic, so you have to make sure that b actually exists." if we add a null/undefined check, this passes fine:

type MyObjectType = {
    a: number;
    b?: number;
}

const obj: MyObjectType = {
    a: 1,
}

if (obj.b != null) {
    console.log(obj.b * 5);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment