Flow este un verificator static de tipuri pentru JavaScript conceput pentru a detecta erorile înainte de rularea codului.
Noțiuni introductive și inferența tipurilor (Getting Started)
/* @flow */
function square (n: number): number {
return n * n
}
const four = square(2)
// Type aliases
type Person = {
name: string,
age: number,
isAdmin: boolean,
likes: Array<string>
}
function greet(user: Person): string {
return `Hello ${user.name}`
}
// Union & Maybe Types
type Status = "pending" | "fulfilled" | "rejected";
type ID = string | number;
let message: ?string = null; // string, null, or undefined
Tipuri de obiecte și forme exacte (Exact Types)
// Width Subtyping (objects allow extra properties by default)
type Named = { name: string }
type PersonInfo = { name: string, age: number }
const p: PersonInfo = { name: "Alice", age: 30 }
const n: Named = p // Valid
// Exact Object Types (disallow unlisted excess properties)
type ExactUser = {|
name: string,
age: number
|}
// Optional object properties
type User = {
name: string,
nickname?: string
}
Tipuri avansate, interfețe și sintaxă de comentarii
// Generics
class Container<T> {
value: T;
constructor(val: T) {
this.value = val;
}
get(): T {
return this.value;
}
}
const box = new Container<number>(123);
// Flow comment syntax (run vanilla JS without transpilation)
/*::
type CustomConfig = {
timeout: number
};
*/
function fetchWithTimeout(url /*: string */) /*: Promise<Response> */ {
// ...
}