Interfaces y Alias de Tipos
## Objetivos de Aprendizaje
- Crear y usar interfaces
- Definir propiedades opcionales y readonly
- Usar tipos de funcion e indexables
- Comprender alias de tipos
- Saber cuando usar cada uno
## Basicos de Interfaces
### Declaracion
```typescript
interface Person {
name: string;
age: number;
}
```
### Implementacion
```typescript
function greet(person: Person): string {
return `Hola, ${person.name}!`;
}
let user: Person = { name: "Alice", age: 30 };
greet(user); // "Hola, Alice!"
```
## Propiedades Opcionales
Propiedades que pueden o no existir:
```typescript
interface User {
name: string;
email?: string;
age?: number;
}
let user1: User = { name: "Bob" };
let user2: User = { name: "Carol", email: "carol@example.com" };
```
## Propiedades Readonly
No pueden ser modificadas despues de la creacion:
```typescript
interface Point {
readonly x: number;
readonly y: number;
}
let point: Point = { x: 10, y: 20 };
// point.x = 15; // Error: No se puede asignar a 'x'
```
## Arrays Readonly
```typescript
interface Config {
readonly options: readonly string[];
}
let config: Config = { options: ["a", "b"] };
// config.options.push("c"); // Error
// config.options = ["x"]; // Error
```
## Tipos de Funcion en Interfaces
### Sintaxis de Metodo
```typescript
interface MathFunc {
(x: number, y: number): number;
}
const add: MathFunc = (a, b) => a + b;
const multiply: MathFunc = (a, b) => a * b;
add(2, 3); // 5
multiply(2, 3); // 6
```
### Firma de Llamada
```typescript
interface Sum {
(a: number, b: number): number;
description: string;
}
const sum: Sum = (a, b) => a + b;
sum.description = "Funcion de suma";
```
## Firmas de Indice
Permitir nombres de propiedad arbitrarios:
```typescript
interface StringMap {
[key: string]: string;
}
let map: StringMap = {};
map["name"] = "Alice";
map["email"] = "alice@example.com";
```
### Con Propiedades Conocidas
```typescript
interface Nested {
[key: string]: number | string;
length: number; // OK: number
name: string; // OK: string | number
}
```
## Herencia de Interfaces
### Extender Interface
```typescript
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
let dog: Dog = {
name: "Buddy",
breed: "Labrador"
};
```
### Herencia Multiple
```typescript
interface A {
a: string;
}
interface B {
b: number;
}
interface C extends A, B {
c: boolean;
}
let obj: C = { a: "hola", b: 42, c: true };
```
## Interface para Clases
### Implementar Interface
```typescript
interface Drawable {
draw(): void;
}
class Circle implements Drawable {
radius: number;
constructor(radius: number) {
this.radius = radius;
}
draw(): void {
console.log(`Dibujando circulo con radio ${this.radius}`);
}
}
```
### Multiples Interfaces
```typescript
interface Printable {
print(): void;
}
interface Serializable {
serialize(): string;
}
class Document implements Printable, Serializable {
print(): void {
console.log("Imprimiendo documento");
}
serialize(): string {
return JSON.stringify(this);
}
}
```
## Alias de Tipos
Nombre para cualquier tipo:
### Sintaxis Basica
```typescript
type ID = string | number;
type Point = { x: number; y: number };
type StringArray = string[];
```
### Con Genericos
```typescript
type Pair = {
first: T;
second: U;
};
let pair: Pair = { first: "edad", second: 30 };
```
### Tipos de Funcion
```typescript
type Callback = (data: string) => void;
function fetchData(callback: Callback): void {
callback("Datos cargados");
}
```
## Interface vs Alias de Tipo
### Interface
```typescript
interface User {
name: string;
}
```
### Alias de Tipo
```typescript
type User = {
name: string;
};
```
### Cuando Usar Interface
- Definir formas de objetos
- Contratos de implementacion de clases
- Fusion de declaraciones
### Cuando Usar Alias de Tipo
- Tipos union
- Tipos tupla
- Alias de primitivos
- Tipos genericos complejos
## Tipos Hibridos
Funcion + objeto:
```typescript
interface Counter {
(start: number): void;
value: number;
reset(): void;
}
function createCounter(): Counter {
let value = 0;
const counter = ((start: number) => {
value = start;
}) as Counter;
counter.value = 0;
counter.reset = () => { value = 0; };
return counter;
}
```
## Extension de Interface de Tipo
```typescript
type Base = {
id: string;
};
interface Extended extends Base {
name: string;
}
let obj: Extended = { id: "123", name: "Alice" };
```
## Fusion de Declaraciones
Interfaces con el mismo nombre se fusionan:
```typescript
interface Window {
title: string;
}
interface Window {
width: number;
}
// Fusionado: { title: string; width: number }
```
## Propiedades de Funcion
```typescript
interface Config {
onLoad: () => void;
onError: (message: string) => void;
data: string[];
}
let config: Config = {
onLoad: () => console.log("Cargado"),
onError: (msg) => console.error(msg),
data: []
};
```
## Resumen
- Las interfaces definen formas de objetos
- Los alias de tipos nombran cualquier tipo
- Usar `?` para propiedades opcionales
- Usar `readonly` para propiedades inmutables
- Las interfaces pueden extender otras interfaces
- Las clases `implementan` interfaces
- Los alias de tipos son mejores para uniones y tuplas
- Las interfaces soportan fusion de declaraciones
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →