Tipos primitivos
TypeScript incluye todos los primitivos de JavaScript y añade anotaciones de tipo adicionales.
// String
let firstName: string = "Alice";
let greeting: string = `Hello, ${firstName}`;
// Number (enteros y decimales)
let age: number = 30;
let price: number = 19.99;
let hex: number = 0xff;
let binary: number = 0b1010;
// Boolean
let isActive: boolean = true;
let hasPermission: boolean = false;
// Null y Undefined
let nothing: null = null;
let notDefined: undefined = undefined;
// BigInt (ES2020+)
let bigNumber: bigint = 9007199254740991n;
// Symbol
let uniqueKey: symbol = Symbol("key");
Arrays
// Dos formas de declarar arrays
let numbers: number[] = [1, 2, 3, 4, 5];
let strings: Array<string> = ["a", "b", "c"];
// Arrays mixtos (evitar cuando sea posible)
let mixed: (string | number)[] = [1, "two", 3];
// Arrays de solo lectura
let readonlyNumbers: readonly number[] = [1, 2, 3];
// readonlyNumbers.push(4); // Error: la propiedad 'push' no existe
// Los métodos de array respetan los tipos
const doubled = numbers.map(n => n * 2); // number[]
const filtered = strings.filter(s => s.length > 1); // string[]
Tuplas
Arrays de longitud fija con tipos específicos en cada posición:
// Tupla: [string, number]
let person: [string, number] = ["Alice", 30];
// Acceder a elementos de la tupla
const name = person[0]; // string
const age = person[1]; // number
// Tupla con elemento opcional
let optionalTuple: [string, number?] = ["Bob"];
// Tupla con elementos rest
let flexibleTuple: [string, ...number[]] = ["scores", 90, 85, 92];
// Tuplas nombradas (TypeScript 4.0+)
type Point = [x: number, y: number];
let coordinates: Point = [10, 20];
// Tupla de solo lectura
const readonlyTuple: readonly [string, number] = ["Alice", 30];
// readonlyTuple[0] = "Bob"; // Error!
Enums
// Enum numérico (por defecto)
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right // 3
}
let move: Direction = Direction.Up;
console.log(Direction.Up); // 0
console.log(Direction[0]); // "Up"
// Enum de strings
enum Status {
Pending = "PENDING",
Active = "ACTIVE",
Completed = "COMPLETED",
Cancelled = "CANCELLED"
}
let orderStatus: Status = Status.Active;
// Enum const (inlineado en compilación)
const enum HttpStatus {
OK = 200,
NotFound = 404,
ServerError = 500
}
// Enum heterogéneo (evitar)
enum Mixed {
No = 0,
Yes = "YES"
}
Any, Unknown, Never y Void
// any - desactiva la verificación de tipos (¡evitar!)
let anything: any = 42;
anything = "string";
anything = true;
anything.nonExistentMethod(); // Sin error, pero falla en tiempo de ejecución
// unknown - any seguro
let uncertain: unknown = 42;
uncertain = "string";
// uncertain.toUpperCase(); // Error: primero debes comprobar el tipo
if (typeof uncertain === "string") {
console.log(uncertain.toUpperCase()); // OK
}
// void - la función no retorna nada
function logMessage(msg: string): void {
console.log(msg);
// sin return
}
// never - la función nunca retorna
function throwError(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while (true) {}
}
Tipo de objeto
// Tipo de objeto en línea
let user: { name: string; age: number } = {
name: "Alice",
age: 30
};
// Propiedades opcionales
let config: { host: string; port?: number } = {
host: "localhost"
// port es opcional
};
// Propiedades de solo lectura
let point: { readonly x: number; readonly y: number } = {
x: 10,
y: 20
};
// point.x = 30; // Error!
// Firmas de índice
let dictionary: { [key: string]: number } = {
apple: 1,
banana: 2,
cherry: 3
};
dictionary["date"] = 4; // OK
Aserciones de tipo
// Aserción de tipo (sabes más que TypeScript)
let someValue: unknown = "Hello, World!";
// Usando sintaxis 'as' (preferida)
let strLength: number = (someValue as string).length;
// Usando sintaxis de ángulo (no en JSX)
let strLength2: number = (<string>someValue).length;
// Aserción de elemento DOM
const input = document.getElementById("myInput") as HTMLInputElement;
input.value = "Hello";
// Aserción non-null (¡usa con cuidado!)
let maybeString: string | null = getValue();
let definitelyString: string = maybeString!; // Asegura que no es null
Tipos literales
// Tipos literales de string
let direction: "north" | "south" | "east" | "west";
direction = "north"; // OK
// direction = "up"; // Error!
// Tipos literales numéricos
let diceRoll: 1 | 2 | 3 | 4 | 5 | 6;
diceRoll = 3; // OK
// diceRoll = 7; // Error!
// Tipos literales booleanos
let trueOnly: true = true;
// Combinando con otros tipos
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
function makeRequest(url: string, method: HttpMethod) {
// ...
}
makeRequest("/api/users", "GET"); // OK
// makeRequest("/api/users", "PATCH"); // Error!
Evita 'any'
Usar any anula el propósito de TypeScript. En su lugar:
- • Usa
unknowncuando no conozcas el tipo - • Usa genéricos para código flexible pero seguro
- • Usa tipos unión para múltiples posibilidades
Puntos clave
- • Usa tipos primitivos: string, number, boolean
- • Los arrays se tipan con
type[]oArray<type> - • Las tuplas son arrays tipados de longitud fija
- • Los enums proporcionan constantes con nombre
- • Prefiere
unknownen lugar deany - • Los tipos literales restringen a valores específicos