Desenvolvimento
TypeScript 5: Novidades e Guia Completo de Migração
25 de setembro de 2025
10 min de leitura
Equipe Dados Educativos
TypeScriptJavaScriptMigraçãoTypesProgramming
TypeScript 5: Novidades e Guia Completo de Migração
TypeScript 5 trouxe melhorias significativas de performance, novos recursos e simplificações. Vamos explorar tudo!
🚀 Principais Novidades
1. Decorators (Stable)
Finalmente decorators estão estáveis e padronizados!
function log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Calling ${propertyKey} with`, args);
return originalMethod.apply(this, args);
};
return descriptor;
}
class Calculator {
@log
add(a: number, b: number) {
return a + b;
}
}
const calc = new Calculator();
calc.add(5, 3); // Log: "Calling add with [5, 3]"
2. const Type Parameters
// Preserva tipos literais
function createArray<const T>(items: readonly T[]) {
return items;
}
const arr = createArray(['a', 'b', 'c']);
// Tipo: readonly ["a", "b", "c"]
// Não apenas: readonly string[]
3. Satisfies Operator Melhorado
type Colors = 'red' | 'green' | 'blue';
const palette = {
red: [255, 0, 0],
green: '#00ff00',
blue: [0, 0, 255]
} satisfies Record<Colors, string | number[]>;
// TypeScript sabe o tipo exato de cada propriedade!
palette.red[0]; // ✅ OK
palette.green.toUpperCase(); // ✅ OK
4. Performance Improvements
- Até 80% mais rápido em projetos grandes
- Menor uso de memória (40-50%)
- Type checking incremental melhorado
5. Better Enum Support
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
// Agora pode usar como tipo literal
type Directions = `${Direction}`;
// "UP" | "DOWN" | "LEFT" | "RIGHT"
📦 Migração - Guia Passo a Passo
Passo 1: Verificar Compatibilidade
# Verificar dependências
npm ls typescript
# Verificar types
npm ls @types/node @types/react
Passo 2: Atualizar TypeScript
npm install -D typescript@5
# Atualizar types também
npm install -D @types/node@latest @types/react@latest
Passo 3: Atualizar tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM"],
"module": "ESNext",
"moduleResolution": "bundler",
// Novo no TS5
"verbatimModuleSyntax": true,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Passo 4: Corrigir Breaking Changes
Lib Updates
// Antes
interface Array<T> {
includes(searchElement: T): boolean;
}
// Agora tipo correto do DOM mudou
// Verificar usos de APIs do browser
Enum Changes
// Pode precisar ajustar enums
enum Status {
Active,
Inactive
}
// Se usar em template literals
const msg = `Status: ${Status.Active}`; // Verificar
Passo 5: Executar Testes
# Compilar
npm run build
# Rodar testes
npm test
# Verificar types
npm run type-check
🛠️ Novos Recursos Úteis
1. Using Declarations
function processFile(path: string) {
using file = openFile(path);
// Arquivo é automaticamente fechado no fim do escopo
return file.read();
} // file.close() chamado automaticamente
2. Import Attributes
// Importar JSON com type safety
import data from './data.json' with { type: 'json' };
// CSS Modules
import styles from './styles.css' with { type: 'css' };
3. Better Inference
// TS5 infere tipos complexos melhor
const users = [
{ name: 'Ana', age: 25, role: 'dev' },
{ name: 'João', age: 30, role: 'designer' }
];
// TS infere automaticamente union types
type Role = typeof users[number]['role'];
// 'dev' | 'designer'
💡 Boas Práticas TypeScript 5
1. Use const Type Parameters
// ✅ Bom - preserva tipos literais
function tuple<const T extends readonly any[]>(...args: T) {
return args;
}
const result = tuple(1, 'hello', true);
// [1, "hello", true] - tipos preservados!
2. Abuse do satisfies
type Route = {
path: string;
method: 'GET' | 'POST';
};
const routes = {
home: { path: '/', method: 'GET' },
login: { path: '/login', method: 'POST' }
} satisfies Record<string, Route>;
// Autocomplete funciona!
routes.home.path;
3. Template Literal Types
type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type Endpoint = `/api/${string}`;
type Route = `${HTTPMethod} ${Endpoint}`;
// "GET /api/users" | "POST /api/users" | ...
🔍 Debugging TypeScript
Ver tipo inferido
// Hover sobre variável no VS Code
const result = complexFunction();
// ^? Ver tipo aqui
Type assertions
// Use satisfies em vez de as
const data = { ... } satisfies Type; // ✅
const data = { ... } as Type; // ❌ menos seguro
Utility Types úteis
// Partial - torna tudo opcional
type PartialUser = Partial<User>;
// Required - torna tudo obrigatório
type RequiredUser = Required<Partial<User>>;
// Pick - seleciona propriedades
type UserPreview = Pick<User, 'id' | 'name'>;
// Omit - remove propriedades
type UserWithoutPassword = Omit<User, 'password'>;
// Record - cria objeto tipado
type UserMap = Record<string, User>;
🎯 Patterns Comuns
1. Discriminated Unions
type Success = {
status: 'success';
data: any;
};
type Error = {
status: 'error';
error: string;
};
type Result = Success | Error;
function handleResult(result: Result) {
if (result.status === 'success') {
console.log(result.data); // ✅ TS sabe que é Success
} else {
console.log(result.error); // ✅ TS sabe que é Error
}
}
2. Builder Pattern
class QueryBuilder<T = {}> {
private query: T;
where<K extends string, V>(key: K, value: V) {
return this as any as QueryBuilder<T & Record<K, V>>;
}
build(): T {
return this.query;
}
}
const query = new QueryBuilder()
.where('age', 25)
.where('name', 'Ana')
.build();
// { age: 25, name: "Ana" }
📚 Recursos para Aprender
Documentação
Prática
Ferramentas
⚠️ Problemas Comuns
1. Tipos implícitos any
// ❌ Problema
function sum(a, b) { // any implícito
return a + b;
}
// ✅ Solução
function sum(a: number, b: number): number {
return a + b;
}
2. Type assertions incorretas
// ❌ Perigoso
const user = JSON.parse(data) as User;
// ✅ Melhor - validar
import { z } from 'zod';
const UserSchema = z.object({
name: z.string(),
age: z.number()
});
const user = UserSchema.parse(JSON.parse(data));
Use nosso Validador de Email para validar dados em projetos!
🎓 Conclusão
TypeScript 5 traz melhorias reais de performance e developer experience. A migração é geralmente suave e vale muito a pena.
Próximos passos:
- Atualizar projeto de teste
- Aprender novos recursos
- Refatorar código antigo
- Compartilhar conhecimento
Teste seus conhecimentos de TypeScript no Quiz de Programação!