Referencia rápida

Hoja de trucos del comprobador de tipos estáticos Flow para JavaScript

Guía de referencia rápida para Flow: comprobador de tipos estáticos en JavaScript con tipos primitivos, objetos exactos, genéricos e interfaces.

· Publicado

Flow es un comprobador de tipos estáticos para JavaScript diseñado para detectar errores antes de la ejecución del código.

Primeros pasos e inferencia de tipos (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

Tipos de objetos y formas exactas (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
}

Tipos avanzados, interfaces y sintaxis de comentarios

// 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> */ {
  // ...
}

Hojas de trucos relacionadas

Temas relacionados