Volver a Fundamentos
Fundamentos — Leccion 7
·20 minObjetos e Interfaces
Define la forma de tus objetos con interfaces.
Objetos tipados
typescript
let persona: { nombre: string; edad: number; activo: boolean } = {
nombre: "Ana",
edad: 25,
activo: true,
};
Interfaces
Para definir la forma de objetos de forma reutilizable.
typescript
interface Persona {
nombre: string;
edad: number;
activo: boolean;
}
let ana: Persona = {
nombre: "Ana",
edad: 25,
activo: true,
};
Propiedades opcionales
typescript
interface Usuario {
nombre: string;
email: string;
telefono?: string; // Opcional
}
let user: Usuario = {
nombre: "Juan",
email: "juan@mail.com",
// telefono es opcional
};
Propiedades readonly
typescript
interface Config {
readonly apiUrl: string;
readonly timeout: number;
}
let config: Config = {
apiUrl: "https://api.example.com",
timeout: 5000,
};
// config.apiUrl = "otra"; // Error: readonly
Interfaces con funciones
typescript
interface Calculadora {
sumar(a: number, b: number): number;
restar(a: number, b: number): number;
}
let calc: Calculadora = {
sumar: (a, b) => a + b,
restar: (a, b) => a - b,
};
Type vs Interface
typescript
// Interface - se puede extender
interface Animal {
nombre: string;
}
interface Perro extends Animal {
raza: string;
}
// Type - más flexible
type Color = "rojo" | "azul" | "verde";
type Punto = { x: number; y: number };
Ejercicio pratico
Crea una interface 'Coche' con marca, modelo y anio. Luego crea un objeto de tipo Coche.
exercise.ts
Loading...
Resultado
Haz clic en "Ejecutar" para ver el resultado...