let nome: string = 'Alfredo';
let idade: number = 30;
let ativo: boolean = true;
let nulo: null = null;
let indefinido: undefined = undefined;
// any — desativa checagem (evitar)
let qualquer: any = 'texto';
// unknown — any seguro, força checagem antes de usar
let entrada: unknown = JSON.parse(dados);
if (typeof entrada === 'string') entrada.toUpperCase();
// never — função que nunca retorna
function erro(msg: string): never { throw new Error(msg); }
// literal types
let status: 'ativo' | 'inativo' | 'pendente' = 'ativo';
let codigo: 200 | 201 | 400 | 404 | 500 = 200;
// tuple
let par: [string, number] = ['Alfredo', 30];
let rgb: [number, number, number] = [255, 128, 0];
3 Arrays e Objetos
const numeros: number[] = [1, 2, 3];
const nomes: Array<string> = ['a', 'b'];
const imutavel: ReadonlyArray<number> = [1, 2, 3];
// objeto inline
const usuario: { nome: string; idade: number; email?: string } = { nome: 'Alfredo', idade: 30 };
// type alias
type Coordenada = { x: number; y: number };
type ID = string | number;
// assertion
const input = document.getElementById('campo') as HTMLInputElement;
4 Interface vs Type
// Interface — para objetos e herança
interface Usuario {
id: number;
nome: string;
email: string;
}
interface Admin extends Usuario { permissoes: string[]; }
// Type — para unions, intersections e aliases
type Status = 'ativo' | 'inativo';
type ID = string | number;
type Resposta<T> = { data: T; erro: null } | { data: null; erro: string };
// Intersection
type AdminUsuario = Usuario & { permissoes: string[] };
// Regra: interface para APIs públicas, type para unions/generics
5 Funções
function somar(a: number, b: number): number { return a + b; }
// opcional e default
function saudar(nome: string, prefixo?: string, pontos: number = 1): string {
return `${prefixo ?? 'Olá'}, ${nome}${'!'.repeat(pontos)}`;
}
// rest
function juntar(sep: string, ...partes: string[]): string { return partes.join(sep); }
// tipo de função
type Handler = (req: Request, res: Response) => void;
// overloads
function processar(entrada: string): string;
function processar(entrada: number): number;
function processar(entrada: string | number): string | number {
if (typeof entrada === 'string') return entrada.trim();
return entrada * 2;
}
6 Generics
// função genérica
function primeiroItem<T>(arr: T[]): T | undefined { return arr[0]; }
// constraint
function tamanho<T extends { length: number }>(item: T): number { return item.length; }
// interface genérica
interface Repositorio<T> {
buscarPorId(id: number): Promise<T | null>;
listar(): Promise<T[]>;
criar(dados: Omit<T, 'id'>): Promise<T>;
atualizar(id: number, dados: Partial<T>): Promise<T>;
deletar(id: number): Promise<void>;
}
// classe genérica
class Stack<T> {
private items: T[] = [];
push(item: T): void { this.items.push(item); }
pop(): T | undefined { return this.items.pop(); }
get tamanho(): number { return this.items.length; }
}
7 Utility Types
interface Produto { id: number; nome: string; preco: number; estoque: number; }
Partial<Produto> // todos opcionais — útil para PATCH
Required<Produto> // todos obrigatórios
Pick<Produto, 'id'|'nome'> // seleciona campos
Omit<Produto, 'id'> // exclui campos — útil para CREATE
Readonly<Produto> // imutável
// Record — dicionário
type EstoquePorCategoria = Record<string, number>;
type CategoriaId = 'eletronicos' | 'roupas';
type MapaCategorias = Record<CategoriaId, Produto[]>;
// ReturnType / Parameters
function buscar() { return { id: 1, nome: 'x' }; }
type ResultadoBusca = ReturnType<typeof buscar>; // { id: number; nome: string }
// NonNullable — remove null e undefined
type SemNull = NonNullable<string | null | undefined>; // string
// Extract / Exclude
type NumOuStr = string | number | boolean;
type ApenasNum = Extract<NumOuStr, number>; // number
type SemBool = Exclude<NumOuStr, boolean>; // string | number
8 Narrowing / Type Guards
// typeof guard
function processar(valor: string | number) {
if (typeof valor === 'string') return valor.toUpperCase();
return valor.toFixed(2);
}
// instanceof
function formatar(erro: Error | string) {
if (erro instanceof Error) return erro.message;
return erro;
}
// discriminated union — mais robusto
type Resultado<T> =
| { ok: true; dados: T }
| { ok: false; erro: string };
function tratar<T>(r: Resultado<T>) {
if (r.ok) console.log(r.dados);
else console.error(r.erro);
}
// type predicate
function ehUsuario(obj: unknown): obj is Usuario {
return typeof obj === 'object' && obj !== null && 'id' in obj;
}
// assertion function
function garantir<T>(v: T | null | undefined, msg: string): asserts v is T {
if (v == null) throw new Error(msg);
}