Son herramientas que ayudan a transformar tipos existentes. Muy útiles para reusar interfaces sin repetir código.
Partial
– todas opcionales
type User = {
id: number;
name: string;
email: string;
};
function updateUser(id: number, data: Partial<User>) {
console.log(`Se actualizo el usuario: ${id} con`, data);
}
updateUser(1, { name: "Luis" }); // ✅
Required
– todas obligatorias
type Config = {
host?: string;
port?: number;
};
function connect(cfg: Required<Config>) {
console.log(`Conectando a ${cfg.host}:${cfg.port}`);
}
connect({ host: "localhost" }); // ❌ Error. falta una propiedad
Readonly
– propiedades inmutables
type User = {
id: number;
name: string;
};
const user: Readonly<User> = {
id: 1,
name: "Luis"
};
user.name = "Pepito"; // ❌ Error
console.log(user);
Pick
– selecciona claves específicas
type User = {
id: number;
name: string;
email: string;
};
type PublicUser = Pick<User, "id" | "name">;
const user: PublicUser = {
id: 1,
name: "Luis"
email: "[email protected]" // ❌ No permitido
};
console.log(user);
Omit
– omite claves específicas
type User = {
id: number;
name: string;
password: string;
};
type SafeUser = Omit<User, "password">;
const user: SafeUser = {
id: 1,
name: "Luis"
password: "test" // ❌ No permitido
};
console.log(user);
Otras utilidades
🔹 Record → { [key: string]: number }
Objeto con claves tipo string
y valores tipo number
const scores: Record<string, number> = {
alice: 10,
bob: 15,
};
🔹 Exclude<"a" | "b", "a"> → "b"
Excluye "a"
del conjunto
type Letters = Exclude<"a" | "b", "a">;
// Resultado: "b"
🔹 Extract<"a" | "b", "a" | "c"> → "a"
Extrae solo "a"
porque está en ambos conjuntos
type Common = Extract<"a" | "b", "a" | "c">;
// Resultado: "a"
🔹 NonNullable → string
Elimina null
y undefined
type Clean = NonNullable<string | null | undefined>;
// Resultado: string
🔹 ReturnType<() => number> → number
Tipo de retorno de una función
function getAge() {
return 30;
}
type Age = ReturnType<typeof getAge>;
// Resultado: number
🔹 Parameters<(a: number, b: string) => void> → [a: number, b: string]
Tupla con los parámetros de la función
type Params = Parameters<(a: number, b: string) => void>;
// Resultado: [number, string]
🔹 ConstructorParameters → [number, number, number, number?, number?, number?, number?]
Parámetros del constructor de Date
type DateArgs = ConstructorParameters<typeof Date>;
// Resultado: los argumentos que acepta new Date(...)
🔹 InstanceType → Date
Tipo de instancia que retorna el constructor
type DateInstance = InstanceType<typeof Date>;
// Resultado: Date
🔹 ThisParameterType<(this: HTMLDivElement, e: MouseEvent) => void> → HTMLDivElement
Extrae el tipo de this
de la función
function handleClick(this: HTMLDivElement, event: MouseEvent) {
this.innerHTML = "Clicked!";
}
type ThisType = ThisParameterType<typeof handleClick>;
// Resultado: HTMLDivElement
🔹 OmitThisParameter<(this: HTMLDivElement, e: MouseEvent) => void> → (e: MouseEvent) => void
Elimina el this
del tipo de función
type WithoutThis = OmitThisParameter<typeof handleClick>;
// Resultado: (e: MouseEvent) => void