TypeScript extends JavaScript by introducing static type checking and comprehensive support for object-oriented programming. By defining types during development, developers can catch errors at compile-time, significantly improving code reliability and maintainability.
Configuration
To initialize a TypeScript project, execute the following command:
tsc --init
For features like BigInt that require modern ECMAScript standards, ensure the lib array in your tsconfig.json includes appropriate targets:
"lib": ["ES2022", "dom"]
Core Primitive Types
In TypeScript, use lowercase identifiers for pirmitive types (e.g., string, number, boolean). Avoid using uppercase wrapper objects unless specifically required for object instances.
let username: string = "dev_user";
let score: number = 42;
let isActive: boolean = true;
Arrays and Tuples
Arrays can be defined with a fixed type or a union of types.
let list: number[] = [10, 20, 30];
let mixedList: (string | number)[] = [1, "text"];
Tuples define an array with a fixed number of elements, each with a specific type:
let coordinate: [number, number] = [10, 20];
coordinate.push(30); // Valid to add, but direct access to indices outside definition is restricted
Enums
Enums allow for named constant sets. They support both forward mapping and reverse mapping.
enum UserRole {
Admin,
Editor,
Viewer
}
// Access value
let role: UserRole = UserRole.Admin;
// Reverse mapping
let roleName: string = UserRole[0];
Advanced Types
- Any: Bypasses type checking entirely.
- Unknown: A safer alternative to
any; it requires type narrowing before performing operations. - Void: Represents the absence of a return value in functions.
- Never: Represents values that never occur, such as functions that always throw errors or enter infinite loops.
function terminate(msg: string): never {
throw new Error(msg);
}
Type Inference
TypeScript automatical infers types when they are not explicitly declaerd:
let count = 100; // Inferred as number
let greeting = "hello"; // Inferred as string
Custom Types and Discriminated Unions
Use type aliases to create reusable type definitions, including discriminated unions for complex state management:
type SuccessResponse = { status: true; data: string };
type ErrorResponse = { status: false; errorCode: number };
type ApiResponse = SuccessResponse | ErrorResponse;
Type Assertions
Assertions manually override the compiler's inference, useful when you possess more information about the type than the compiler can derive.
const container = document.getElementById('container');
// Non-null assertion
container!.classList.add('active');
// Type casting
(container as HTMLDivElement).style.display = 'block';