TypeScript Course
Cheatsheet
A quick reference — the essential syntax of modern TypeScript on a single page. Press Ctrl/Cmd + P to print it.
TypeScript · Cheatsheet — eLearner.app
Annotations and Primitive Types
Explicit annotation
const username: string = "Alice"; const score: number = 100; const isActive: boolean = true;Add a colon (:) followed by the type after the variable name.
Type inference
const inferredName = "Bob"; // Inferred as string let inferredNum = 42; // Inferred as numberTypeScript automatically deduces the type based on the initial value.
Arrays and Tuples
Arrays (homogeneous)
const numbers: number[] = [1, 2, 3]; const strings: Array<string> = ["a", "b", "c"];Two equivalent syntaxes to define collections of the same type.
Tuples (fixed size)
const response: [number, string] = [200, "OK"]; const point: [number, number, number] = [10, 20, 30];Fixed-position elements with specific types.
Type Aliases and Interfaces
Interfaces
interface User { id: number; username: string; email?: string; // Optional property }Best for defining objects that can be extended using inheritance (extends).
Type Aliases
type Point2D = { x: number; y: number; }; type ID = string | number; // UnionAllows renaming any type or defining unions/intersections.
Unions and Narrowing
Union Types
let id: string | number; id = "ABC"; // OK id = 123; // OKAllows a variable to accept multiple alternative types.
Type Narrowing
function printId(id: string | number) { if (typeof id === "string") { console.log(id.toUpperCase()); // id is string } else { console.log(id.toFixed()); // id is number } }Enables invoking type-specific methods by isolating the type at runtime.
Typed Functions
Parameters and return annotations
function greet(name: string, prefix?: string): string { return prefix ? `Hello, ${prefix} ${name}` : `Hello, ${name}`; }Use a question mark (?) to mark a parameter as optional.
Function Type (Signature)
type MathOp = (a: number, b: number) => number; const add: MathOp = (x, y) => x + y;Extracts a function signature into a reusable type.
Generics
Generic Function
function identity<T>(arg: T): T { return arg; } const val = identity<number>(42);Makes the function flexible while keeping type safety intact.
Generic Interface
interface Box<T> { content: T; } const stringBox: Box<string> = { content: "Book" };Allows the internal property to adapt to the specified type.
Classes and Modifiers
Parameter properties
class User { constructor(public username: string, private role: string) {} }Concise syntax: automatically declares and initializes class fields.
Abstract Classes
abstract class Shape { abstract getArea(): number; } class Circle extends Shape { constructor(public radius: number) { super(); } getArea() { return Math.PI * this.radius ** 2; } }Cannot be directly instantiated, serve as blueprints for subclasses.
Utility Types
Partial and Readonly
interface Task { id: number; title: string; } type PartialTask = Partial<Task>; // Makes all fields optional type ReadonlyTask = Readonly<Task>; // Prevents property mutationsBuilt-in utilities to transform property structures easily.
Pick and Omit
interface User { id: number; name: string; email: string; } type UserInfo = Pick<User, "name" | "email">; // Extracts fields type NewUser = Omit<User, "id">; // Excludes fieldsAllow selection or exclusion of specific fields.
Advanced Types and Guards
Custom Type Guards
function isString(val: unknown): val is string { return typeof val === "string"; }Use the 'x is Type' predicate to force narrowing in the caller scope.
Literal Types and Const
type Direction = "up" | "down"; const config = { host: "localhost", port: 8080 } as const; // Makes the entire object readonlyUnions of precise values and as const modifier for deep immutability.
Template Literal Types
type Status = "success" | "error"; type Action = "click" | "hover"; type Event = \`\${Status}-\${Action}\`;Builds new string types by interpolating string literal unions.