Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónTASTEWINMGestión de archivosHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoInversiónTASTESTOCKAplicación de escritorio de trading automático de accionesEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguroTASTEWINMUn gestor de archivos de dos paneles pensado para el teclado

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Inversión

TASTESTOCKTrading automático de acciones según las reglas que tú defines: cuándo y qué

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasQuiénes somosPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
Ayer
Vistas totales
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de TypeScript
TypeScript
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts: The Type System
Debates

Guía de TypeScript · 6/6

Key Concepts: The Type System

Por ahora, este capítulo solo está disponible en inglés.

TypeScript's real power lives in its type system. This chapter digs into generics for reusable types, narrowing and type guards that follow your control flow, discriminated unions for modeling state safely, utility types for transforming existing types, and the strict mode settings that make all of it trustworthy.

Generics

Generics let a function or type take a type as a parameter, so it can work with many types without forgetting which one it was given. Constrain a type parameter with extends, and combine it with keyof to tie an object's keys to their value types.

function first<T>(items: T[]): T | undefined {
  return items[0];
}
const n = first([1, 2, 3]);       // number | undefined
const s = first(["a", "b"]);      // string | undefined

function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}
longest("hello", "hi");           // string
longest([1, 2], [1, 2, 3]);       // number[]

function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}
const user = { name: "Kim", age: 30 };
const age = getProp(user, "age"); // number
// getProp(user, "email");        // error: not a key of user

interface ApiResponse<T> {
  data: T;
  status: number;
}

With any you could accept anything, but the return type would be lost. Generics keep both flexibility and safety.

Narrowing and type guards

A value with a union type gets refined to something more specific as it passes through checks. The compiler understands typeof, instanceof, the in operator, equality comparisons, and truthiness checks. To turn your own checking function into a type guard, give it a type predicate of the form value is Type as its return type.

interface Cat { meow(): void }
interface Dog { bark(): void }

function speak(pet: Cat | Dog) {
  if ("meow" in pet) pet.meow();  // Cat
  else pet.bark();                // Dog
}

function isString(value: unknown): value is string {
  return typeof value === "string";
}

function shout(input: unknown) {
  if (isString(input)) {
    console.log(input.toUpperCase()); // narrowed to string
  }
}

function len(text: string | null): number {
  if (!text) return 0;            // filters out null and ""
  return text.length;             // string
}

Discriminated unions

A discriminated union is a union whose members share a property, usually called kind or type, holding a different literal value in each member. Switch on that property and every branch knows the exact member it is dealing with. Assigning to never in the default branch turns forgotten cases into compile errors when the union grows.

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; size: number }
  | { kind: "rect"; width: number; height: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle": return Math.PI * shape.radius ** 2;
    case "square": return shape.size ** 2;
    case "rect":   return shape.width * shape.height;
    default: {
      const unreachable: never = shape; // errors if a case is missing
      return unreachable;
    }
  }
}
¿Tienes preguntas sobre este capítulo?
Capítulo anteriorErrors and Testing

This pattern shines for UI states such as loading, success, and failure, and for message types exchanged with a server.

Utility types

TypeScript ships a set of built-in utility types that derive new types from existing ones.

UtilityEffect
Partial<T>Makes every property optional
Required<T>Makes every property required
Readonly<T>Makes every property read-only
Pick<T, K> and Omit<T, K>Keep or drop selected properties
Record<K, V>An object with keys K and values V
ReturnType<F> and Parameters<F>A function's return and parameter types
Awaited<T>The value a Promise resolves to
interface Todo {
  id: number;
  title: string;
  done: boolean;
}

type TodoPatch = Partial<Omit<Todo, "id">>;  // title?, done?
type TodoPreview = Pick<Todo, "id" | "title">;
type ByStatus = Record<"open" | "closed", Todo[]>;

function update(todo: Todo, patch: TodoPatch): Todo {
  return { ...todo, ...patch };
}

const config = {
  port: 3000,
  mode: "dev",
} satisfies Record<string, string | number>;

The satisfies operator at the end validates a value against a type while keeping the narrower inferred type, instead of widening the variable to the annotation.

Strict mode

"strict": true turns on a family of checks at once. The ones that matter most:

  • strictNullChecks treats null and undefined as distinct types, so you cannot use a possibly missing value without checking it.
  • noImplicitAny stops parameters and variables from silently falling back to any.
  • strictPropertyInitialization verifies that class properties are assigned in the constructor.
  • useUnknownInCatchVariables types catch variables as unknown.

Some useful checks live outside the strict family. noUncheckedIndexedAccess, for example, adds undefined to values read through array indexes or index signatures.

Summary

  • Generics build reusable functions and types without losing type information.
  • Narrowing refines unions through typeof, instanceof, in, and more; value is T creates custom guards.
  • Discriminated unions plus a never check guarantee every case is handled.
  • Utility types such as Partial, Pick, Omit, and Record reshape existing types.
  • Keep strict on, always.

Where to go next in the official documentation:

  • The TypeScript Handbook
  • Generics
  • Narrowing
  • Utility Types
  • TSConfig Reference
  • TypeScript Playground

0 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.