TypeScript Avançado
TypeScript oferece recursos poderosos como Generics e Utility Types que podem melhorar drasticamente a qualidade do código.
Generics
// Função genérica para arrays
function getFirst<T>(items: T[]): T | undefined {
return items[0];
}
const numbers = [1, 2, 3];
const firstNumber = getFirst(numbers); // number | undefined
const strings = ['a', 'b', 'c'];
const firstString = getFirst(strings); // string | undefinedUtility Types
interface User {
id: number;
name: string;
email: string;
password: string;
}
// Partial: Todas propriedades opcionais
type PartialUser = Partial<User>;
// Pick: Seleciona propriedades específicas
type UserPublic = Pick<User, 'id' | 'name' | 'email'>;
// Omit: Remove propriedades específicas
type UserWithoutPassword = Omit<User, 'password'>;Conditional Types
type NonNullable<T> = T extends null | undefined ? never : T;
type UserName = NonNullable<string | null>; // string
0 comments