TypeScript Essentials
TypeScript Basic Types
TypeScript Basic Types
Section titled “TypeScript Basic Types”TypeScript provides static typing through type annotations.
Primitive Types
Section titled “Primitive Types”// Stringlet firstName: string = "John";
// Numberlet age: number = 25;let price: number = 99.99;
// Booleanlet isActive: boolean = true;
// Null and Undefinedlet nothing: null = null;let notDefined: undefined = undefined;
// Symbollet sym: symbol = Symbol("key");
// BigIntlet big: bigint = 100n;Arrays
Section titled “Arrays”// Array of numberslet numbers: number[] = [1, 2, 3];
// Generic syntaxlet names: Array<string> = ["Alice", "Bob"];
// Mixed arrays (avoid if possible)let mixed: (string | number)[] = [1, "two", 3];
// Readonly arrayslet readOnly: readonly number[] = [1, 2, 3];Tuples
Section titled “Tuples”// Fixed-length array with specific typeslet person: [string, number] = ["Alice", 25];
// Named tuples (TypeScript 4.0+)let user: [name: string, age: number] = ["Bob", 30];
// Optional elementslet optional: [string, number?] = ["Alice"];// Numeric enumenum Direction { Up, // 0 Down, // 1 Left, // 2 Right // 3}
// String enumenum Status { Active = "ACTIVE", Inactive = "INACTIVE", Pending = "PENDING"}
// Usagelet dir: Direction = Direction.Up;Special Types
Section titled “Special Types”// Any - avoid when possiblelet anything: any = "string";anything = 42;anything = true;
// Unknown - safer than anylet value: unknown = "hello";if (typeof value === "string") { console.log(value.toUpperCase());}
// Void - no return valuefunction log(msg: string): void { console.log(msg);}
// Never - never returnsfunction error(msg: string): never { throw new Error(msg);}Type Assertions
Section titled “Type Assertions”// Angle bracket syntaxlet value: unknown = "hello";let length: number = (<string>value).length;
// as syntax (preferred in JSX)let length2: number = (value as string).length;
// Non-null assertionlet el = document.getElementById("app")!;