Basics
TypeScript types, interfaces, functions, and generics.
Types
// Primitives
let name: string = "Ada";
let age: number = 30;
let active: boolean = true;
// Arrays
let items: string[] = ["a", "b"];
let numbers: Array<number> = [1, 2, 3];
// Tuples
let pair: [string, number] = ["Ada", 30];
// Union
let id: string | number = "abc";
id = 123;
// Literal
let status: "active" | "inactive" = "active";
// Any & Unknown
let data: any = "anything"; // escape hatch
let safe: unknown = "safer"; // type-safe any
Interfaces
interface Person {
name: string;
birthYear: number;
readonly id: number;
email?: string; // optional
}
const p: Person = { name: "Ada", birthYear: 1985, id: 1 };
Extending
interface Employee extends Person {
company: string;
}
Type Aliases
type Status = "active" | "inactive";
type ID = string | number;
type Point = {
x: number;
y: number;
};
Functions
function greet(name: string): string {
return `Hello, ${name}`;
}
// Arrow
const add = (a: number, b: number): number => a + b;
// Optional & default params
function build(name: string, active: boolean = true): void { ... }
// Overloads
function parse(input: string): number;
function parse(input: number): string;
function parse(input: string | number): string | number { ... }
Generics
function first<T>(items: T[]): T | undefined {
return items[0];
}
first([1, 2, 3]); // number
first(["a", "b"]); // string
Next: Conditions & Switches