2.5 KiB
2.5 KiB
title |
---|
Flow |
Simple failing example
/* @flow */
function foo(x) { return x * 10; }
foo('Hello, world!');
Annotations
// Simple
function foo(x: string, y: number): string { ... }
// Arrays
function total(numbers: Array<number>) { ... }
Primitives
any
boolean
mixed
number
string
void // undefined
null // null (but not undefined)
?number // maybe (number | void | null)
{a: Number} // object with a shape
[any, number] // tuples (fixed-length arrays)
Array<T>
Class<T>
Function
Object
Dynamic object keys
type Items = {
[key: string]: Item
}
Enums
type Suit = "Diamonds" | "Clubs" | "Hearts" | "Spades"
const countries = {
US: "United States",
IT: "Italy",
FR: "France"
}
type Country = $Keys<typeof countries>
Type aliases
type Tree = {
foo: string,
bar: number,
qux: (foo: string, bar: number) => boolean
}
type Generic<T> = {
foo: T
}
Generic classes
class GenericClass<T> {
x: T;
constructor (x: T) { ... }
}
var n: GenericClass<number> = new GenericClass(0)
Interfaces
interface Jsonable {
toJSON(): string
}
class Foo {
toJSON() { return '{}' }
}
(new Foo: Jsonable)
Functions
const callback: () => void = function () {}
function filter<T> (list: Array<T>, callback: (item: T) => boolean): Array<T> {
}
Imports
import type { Person } from '../person'
import typeof Config from '../config'
export type Person = { id: string }
Examples
var myNumbers: Array<number> = [42]
function foo(): any { return 42 }
var b: boolean = false
var b: ?boolean = false /* maybe */
var b: string | boolean = false /* maybe */
var a: Class<MyClass> = MyClass
var b: MyClass = new a()
// Function signature
var add: ((num1: number, num2: number) => number) = function(num1, num2) {
return num1 + num2;
};
Comment syntax
/*::
export type Foo = { ... }
*/
function add(n /*: number */) { ... }
React
React$Element<any>
class Foo extends React.Component {
/*:: state: { open: boolean } */
/*:: props: { open: boolean } */
}