mirror of
https://github.com/onkelbeh/cheatsheets.git
synced 2025-06-15 14:47:53 +02:00
3.5 KiB
3.5 KiB
title | layout | category | updated |
---|---|---|---|
Flow | 2017/sheet | JavaScript libraries | 201708 |
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
Type | Description |
---|---|
any |
|
boolean |
|
mixed |
|
number |
|
string |
|
void |
undefined |
null |
null (but not undefined) |
--- | --- |
{a: Number} |
Object with a shape |
[any, number] |
Tuples (fixed-length arrays) |
--- | --- |
Array<T> |
|
Class<T> |
|
Function |
|
Object |
|
--- | --- |
?number |
Maybe (number, void, null) |
`a | b` |
Dynamic keys
type Items = {
[key: string]: Item
}
See: Dynamic object keys
Enums
type Suit = "Diamonds" | "Clubs" | "Hearts" | "Spades"
const countries = {
US: "United States",
IT: "Italy",
FR: "France"
}
type Country = $Keys<typeof countries>
See: Enums
Type aliases
type Tree = {
foo: string,
bar: number,
qux: (foo: string, bar: number) => boolean
}
type Generic<T> = {
foo: T
}
See: Type aliases
Generic classes
class GenericClass<T> {
x: T
constructor (x: T) { ... }
}
var n: GenericClass<number> = new GenericClass(0)
See: Generic classes
Interfaces
interface Jsonable {
toJSON(): string
}
class Foo {
toJSON() { return '{}' }
}
(new Foo: Jsonable)
See: Interfaces
Functions
const callback: () => void = function () {}
function filter<T> (
list: Array<T>,
callback: (item: T) => boolean
): Array<T> {
···
}
See: Functions
Imports
import type { Person } from '../person'
import typeof Config from '../config'
export type Person = { id: string }
Comment syntax
/*::
export type Foo = { ... }
*/
function add(n /*: number */) { ... }
React
React$Element<any>
class Foo extends React.Component {
/*:: state: { open: boolean } */
/*:: props: { open: boolean } */
}
Examples
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
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
}
You don't need to do this! It's inferred. This is better:
var add = function (num1: number, num2: number) {
return num1 + num2
}