TechLead
📘
Intermedio
13 min lectura

Preguntas de Entrevista TypeScript

Tipos de TypeScript, interfaces, genéricos y conceptos avanzados

Preguntas Esenciales de Entrevista TypeScript

Domina los conceptos de TypeScript comúnmente preguntados en entrevistas frontend. Esta guía cubre tipos, interfaces, genéricos, utility types y características avanzadas.

1. Tipos Básicos en TypeScript

// Tipos primitivos
let nombre: string = 'Juan';
let edad: number = 30;
let activo: boolean = true;
let nada: null = null;
let indefinido: undefined = undefined;

// Arrays
let numeros: number[] = [1, 2, 3];
let strings: Array = ['a', 'b', 'c'];

// Tuple - longitud y tipos fijos
let tupla: [string, number] = ['Juan', 30];
let rgb: [number, number, number] = [255, 0, 0];

// Enum
enum Rol {
  Admin = 'ADMIN',
  Usuario = 'USUARIO',
  Invitado = 'INVITADO'
}
let rolUsuario: Rol = Rol.Admin;

// Any - evitar si es posible
let cualquiera: any = 'hola';
cualquiera = 42; // Sin verificación de tipo

// Unknown - más seguro que any
let valor: unknown = 'hola';
if (typeof valor === 'string') {
  console.log(valor.toUpperCase()); // Requiere type guard
}

// Void - sin valor de retorno
function log(mensaje: string): void {
  console.log(mensaje);
}

// Never - nunca retorna
function lanzarError(mensaje: string): never {
  throw new Error(mensaje);
}

2. Interface vs Type

// Interface - para formas de objetos
interface Usuario {
  id: number;
  nombre: string;
  email?: string; // Opcional
  readonly creadoEn: Date; // Solo lectura
}

// Extensión de interface
interface Admin extends Usuario {
  rol: 'admin';
  permisos: string[];
}

// Fusión de interface (declaration merging)
interface Usuario {
  edad: number; // Se agrega a la interface Usuario
}

// Type alias - más flexible
type ID = string | number;
type Callback = (data: string) => void;

// Union types
type Estado = 'cargando' | 'éxito' | 'error';

// Intersection types
type UsuarioConFecha = Usuario & { ultimoAcceso: Date };

// Type vs Interface
// Usa Interface para objetos y clases
// Usa Type para unions, intersections, y tipos complejos

3. Genéricos

// Función genérica
function identidad(arg: T): T {
  return arg;
}

const num = identidad(42);
const str = identidad('hola');

// Interface genérica
interface Respuesta {
  datos: T;
  estado: number;
  mensaje: string;
}

const respuesta: Respuesta = {
  datos: { id: 1, nombre: 'Juan' },
  estado: 200,
  mensaje: 'OK'
};

// Clase genérica
class Cola {
  private items: T[] = [];
  
  enqueue(item: T): void {
    this.items.push(item);
  }
  
  dequeue(): T | undefined {
    return this.items.shift();
  }
}

Mejores Prácticas de TypeScript

  • ✓ Habilita strict mode en tsconfig.json
  • ✓ Evita usar any siempre que sea posible
  • ✓ Usa unknown en lugar de any
  • ✓ Define tipos para props de componentes React
  • ✓ Usa utility types (Partial, Pick, Omit, etc.)
  • ✓ Documenta tipos complejos con comentarios
  • ✓ Usa type guards para narrowing