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 · 2/6

Syntax Basics

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

TypeScript's syntax is JavaScript's syntax. What it adds is a way to describe the types of variables, parameters, and return values. This chapter covers declarations, functions, arrow functions, and control flow, along with a practical rule of thumb for when to write types yourself and when to let the compiler infer them.

let and const

Declare variables with let or const. A const binding cannot be reassigned; a let binding can. Both are block-scoped, meaning they only exist inside the nearest pair of braces. The legacy var keyword is function-scoped and full of surprises, so leave it out of new code.

const appName = "TASTEDEV";   // cannot be reassigned
let count = 0;                // can change
count += 1;

const user = { name: "Kim", age: 30 };
user.age = 31;                // fine: properties are still mutable
// user = { name: "Lee", age: 20 }; // error: cannot assign to a const

if (count > 0) {
  const inner = "only visible inside this block";
  console.log(inner);
}

Note that const locks the binding, not the object it points to. A good default is to reach for const everywhere and switch to let only when a value genuinely needs to change. Readers then know at a glance which names can move.

Annotations and inference

Writing : Type after a name is a type annotation. Most of the time you can skip it, because TypeScript infers the type from the initial value.

let title: string = "Guide"; // annotated, but redundant
let pages = 120;              // inferred as number
const lang = "en";            // inferred as the literal type "en"

let total: number;            // no initializer, so annotate
total = pages * 2;

// pages = "many"; // error: string is not assignable to number

Because pages is a let, it gets the wide type number. lang is a const that can never change, so its type is the exact value "en". That is called a literal type, and it becomes important in chapters 3 and 6.

Places where an explicit annotation pays off:

  • Function parameters. There is nothing to infer from, so always annotate them.
  • Return types of exported functions. They act as a contract and stop accidental changes.
  • Variables declared without a value, and empty arrays you fill in later.

Functions

Annotate each parameter, and optionally the return type after the parameter list. Mark a parameter optional with ?, or give it a default value.

function add(a: number, b: number): number {
  return a + b;
}

function formatName(first: string, last?: string): string {
  return last ? `${first} ${last}` : first;
}

function repeat(text: string, times = 2): string {
  return text.repeat(times); // times is inferred as number
}

function sum(...values: number[]): number {
  return values.reduce((acc, v) => acc + v, 0);
}

function log(message: string): void {
  console.log(message); // no return value, so void
}

add(1, 2);           // 3
formatName("Ada");   // "Ada"
sum(1, 2, 3, 4);     // 10
¿Tienes preguntas sobre este capítulo?
Capítulo anteriorGetting StartedCapítulo siguienteTypes and Data

Unlike plain JavaScript, TypeScript checks the number of arguments too. Calling add(1) is an error; if a parameter may be omitted, say so with ? or a default.

Arrow functions

Arrow functions are compact and do not bind their own this, which makes them ideal for callbacks. When you pass an arrow function as a callback, its parameter types are inferred from context, so you rarely need to annotate them.

const square = (n: number): number => n * n;

const toUpper = (s: string) => s.toUpperCase(); // return type inferred

const scores = [72, 95, 88];
const passed = scores.filter((score) => score >= 80); // score: number
const labels = scores.map((score, index) => `#${index + 1}: ${score}`);

type Comparator = (a: number, b: number) => number;
const ascending: Comparator = (a, b) => a - b;
console.log([...scores].sort(ascending));

Naming a function shape, as Comparator does here, lets you reuse the same signature across many functions.

Control flow

Conditionals and loops work exactly as in JavaScript. Use === and !== for comparisons; they never coerce types behind your back.

function grade(score: number): string {
  if (score >= 90) {
    return "A";
  } else if (score >= 80) {
    return "B";
  }
  return "C";
}

function dayName(day: number): string {
  switch (day) {
    case 0: return "Sunday";
    case 6: return "Saturday";
    default: return "Weekday";
  }
}

const fruits = ["apple", "pear", "persimmon"];
for (const fruit of fruits) {
  console.log(fruit);            // iterates over values
}
for (let i = 0; i < fruits.length; i++) {
  console.log(i, fruits[i]);
}

let n = 3;
while (n > 0) {
  n--;
}

const status = n === 0 ? "done" : "running";

For arrays, for...of is the most readable loop. Avoid for...in on arrays: it walks over keys as strings, not values.

Summary

  • Default to const, use let when a value must change, and skip var.
  • Let inference handle initialized variables; annotate parameters and exported return types.
  • Express optional parameters with ?, defaults with =, and rest parameters with ....
  • Callback parameters in arrow functions pick up their types from context.
  • Compare with ===, and loop over arrays with for...of.

0 comentarios

Comentarios destacadosMás recientes primero

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