Skip to content

Instantly share code, notes, and snippets.

@nicolashery
Last active October 28, 2015 17:48
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 nicolashery/4319ac66ae779e703072 to your computer and use it in GitHub Desktop.
Save nicolashery/4319ac66ae779e703072 to your computer and use it in GitHub Desktop.
Flow playground (flowtype.org)
/* @flow */
import _ from "lodash";
type UserId = string;
type UserRole =
'admin' |
'guest' |
'member';
type User = {
id: UserId,
firstName: string,
lastName: string,
role: UserRole,
age: ?number
};
var users: User[] = [
{
id: '123',
firstName: 'Bob',
lastName: 'Smith',
role: 'admin',
age: null
},
{
id: '456',
firstName: 'Jane',
lastName: 'Clark',
// role: 'foo', // throws
role: 'guest',
age: 23
}
];
var u1 = _.first(users);
// u1.firstName; // throws
if (u1) {
// u1.name; // throws
u1.firstName
};
var u2 = _.last(users);
if (u2) {
u2.firstName;
}
var u3: User = {
id: '789',
firstName: 'Harry',
lastName: 'Potter',
role: 'member',
age: null
};
// Object.assign(u3, {foo: 'guest'}); // throws
// Object.assign(u3, {role: 'foo'}); // throws
// var u4: User = Object.assign({}, u3, {role: 'foo'}); // throws
Object.assign(u3, {role: 'guest'});
// var u5 = _.find(users, (user) => user.name === 'Bob'); // throws
var u5 = _.find(users, (user) => user.firstName === 'Bob');
if (u5) {
// u5.name; // throws
u5.firstName;
}
var admins = users.filter(user => user.role === 'admin');
var u6 = _.first(admins);
if (u6) {
// u6.name; // throws
u6.firstName;
}
// ----------------------------------------------------------------------------
/* @flow */
import React from "react";
type Props = {
width: number,
text: string
};
// Class components
// https://github.com/facebook/flow/issues/398
class LabelClass extends React.Component {
props: Props;
static defaultProps: {}; // Flow needs this to work (for now)
render() {
return <div style={{width: this.props.width * 2}}>{this.props.text}</div>;
}
}
<LabelClass width="100px" height="20px" />; // type check error
// Function components
function LabelFunction(props: Props) {
return <div style={{width: props.width * 2}}>{props.text}</div>;
}
LabelFunction({width: "100px", height: "20px"}); // type check error
// interfaces/lodash.js
declare module lodash {
declare function first<T>(array: T[]): ?T;
declare function last<T>(array: T[]): ?T;
declare function find<T>(
array: T[],
predicate: (value: T, index: number) => boolean
): ?T
}
[ignore]
.*\/node_modules\/
[include]
[libs]
interfaces/
[options]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment