TS Quick Reference
Everything you need day‑to‑day – types, classes, generics, and modern features.
Basic Types
Primitives
string– "hello"number– 42, 3.14boolean– true, falsebigint– 100nsymbol– unique identifiernull/undefined
Complex Types
any– opt out of type checkingunknown– type‑safe anyvoid– no return valuenever– function never returnsobject– non‑primitiveArray<T>orT[]Tuple– fixed‑length arrayEnum– named constants
Type Declarations
let name: string = "Alice"; let age: number = 25; let isActive: boolean = true; let list: number[] = [1, 2, 3]; let tuple: [string, number] = ["Alice", 25];
Enums
// Numeric enum (auto‑incremented) enum Color { Red = 0, Green = 1, Blue = 2 } let c: Color = Color.Green; // String enum enum Status { Success = "SUCCESS", Failure = "FAILURE", Pending = "PENDING" } // Const enum (inlined at compile time) const enum Direction { Up = "UP", Down = "DOWN" }
Interfaces
// Basic interface interface Person { name: string; age: number; email?: string; // optional readonly id: number; // read‑only } // Interface with method interface Greetable { greet(): void; } // Extending interfaces interface Employee extends Person, Greetable { department: string; salary: number; } // Index signature interface StringMap { [key: string]: string; } // Function interface interface SearchFunc { (source: string, substring: string): boolean; }
Interface vs Type
// Use interface for objects that can be extended interface Animal { name: string; } // Use type for unions, intersections, primitives, etc. type ID = string | number; type Point = { x: number; y: number };
Type Aliases
// Primitive alias type UserID = string; // Union type type Status = "pending" | "approved" | "rejected"; // Intersection type type FullPerson = Person & { department: string }; // Type with generics type Response<T> = { data: T; status: number; error?: string; };
Classes
class Animal { private name: string; // accessible only inside class protected age: number; // accessible in subclasses public species: string; // accessible anywhere (default) constructor(name: string, age: number, species: string) { this.name = name; this.age = age; this.species = species; } public speak(): void { console.log(`${this.name} makes a sound`); } } // Inheritance class Dog extends Animal { private breed: string; constructor(name: string, age: number, breed: string) { super(name, age, "canine"); this.breed = breed; } public override speak(): void { console.log(`${this.name} barks!`); } } // Abstract class abstract class Shape { abstract area(): number; } class Circle extends Shape { constructor(private radius: number) { super(); } public area(): number { return Math.PI * this.radius ** 2; } }
Functions
// Type annotations function add(a: number, b: number): number { return a + b; } // Arrow function const multiply = (a: number, b: number): number => a * b; // Optional and default parameters function greet(name: string, greeting: string = "Hello"): string { return `${greeting}, ${name}`; } // Rest parameters function sum(...numbers: number[]): number { return numbers.reduce((acc, n) => acc + n, 0); } // Function overloads function process(value: string): string; function process(value: number): number; function process(value: any): any { if (typeof value === "string") { return value.toUpperCase(); } if (typeof value === "number") { return value * 2; } } // Void return function logMessage(msg: string): void { console.log(msg); }
Generics
// Generic function function identity<T>(value: T): T { return value; } let num = identity<number>(42); // explicit let str = identity("hello"); // inferred // Generic interface interface Box<T> { value: T; getValue(): T; } // Generic class class Stack<T> { private items: T[] = []; public push(item: T): void { this.items.push(item); } public pop(): T | undefined { return this.items.pop(); } } // Generic constraints function getLength<T extends { length: number }>(obj: T): number { return obj.length; }
Utility Types
Common Utilities
Partial<T>– all properties optionalRequired<T>– all properties requiredReadonly<T>– all properties read‑onlyPick<T, K>– select specific keysOmit<T, K>– exclude specific keysRecord<K, T>– object with keys K of type T
Advanced Utilities
Exclude<T, U>– remove types from T that are assignable to UExtract<T, U>– extract types from T that are assignable to UNonNullable<T>– remove null and undefinedReturnType<T>– return type of a functionParameters<T>– tuple of function parametersAwaited<T>– unwrap Promises
Examples
interface User {
id: number;
name: string;
email: string;
age?: number;
}
type UserPartial = Partial<User>; // all optional
type UserReadonly = Readonly<User>; // all read‑only
type UserNameOnly = Pick<User, "name">; // { name: string }
type UserNoAge = Omit<User, "age">; // without age
type UserMap = Record<"admin" | "user", User>;
Type Guards & Narrowing
// typeof guard function isString(value: unknown): value is string { return typeof value === "string"; } // instanceof guard function isDog(animal: Animal): animal is Dog { return animal instanceof Dog; } // In operator if ("speak" in animal) { animal.speak(); } // User‑defined type guard function isValidPerson(obj: any): obj is Person { return obj typeof "object" && "name" in obj && "age" in obj; } // Narrowing with type predicates function processValue(value: string | number) { if (typeof value === "string") { console.log(value.toUpperCase()); } else { console.log(value.toFixed(2)); } }
Decorators (Experimental)
// Class decorator function sealed(constructor: Function) { Object.seal(constructor); Object.seal(constructor.prototype); } @sealed class MyClass {} // Method decorator function log(target: any, propertyKey: string, descriptor: PropertyDescriptor) { const original = descriptor.value; descriptor.value = function(...args: any[]) { console.log(`Calling ${propertyKey} with`, args); return original.apply(this, args); }; } class Example { @log public greet(name: string): string { return `Hello, ${name}`; } }
Modules
// Exporting export interface User { id: number; name: string; } export const API_URL = "https://api.example.com"; export default class UserService { public getUser(id: number): User { return { id, name: "Alice" }; } } // Importing import UserService, { User, API_URL } from "./UserService"; import * as Utils from "./utils"; // namespace import // Re‑export export * from "./types"; export { User } from "./models";
Type Declarations (.d.ts)
// ambient declaration declare module "my-library" { export function doSomething(): void; export interface Config { debug: boolean; } } // global declarations declare global { interface Window { MY_APP_CONFIG: { version: string; }; } }
Conditional Types
// Basic conditional type type IsString<T> = T extends string ? true : false; type A = IsString<"hello">; // true type B = IsString<number>; // false // Type inference with infer type ElementType<T> = T extends (infer U)[] ? U : never; type C = ElementType<string[]>; // string // Distributive conditional types type ToArray<T> = T extends any ? T[] : never; type D = ToArray<string | number>; // string[] | number[]
Mapped Types
// Basic mapped type type ReadonlyFields<T> = { readonly [K in keyof T]: T[K]; }; // With property modifiers type NullableFields<T> = { [K in keyof T]: T[K] | null; }; // Key remapping type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]; };
tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020", "DOM"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
Best Practices
- Use
unknowninstead ofany–unknownis type‑safe,anyopts out of type checking. - Enable
strictmode in tsconfig.json for full type safety. - Use
interfacefor objects that can be extended; usetypefor unions, intersections, and primitives. - Use
readonlyfor properties that should not be mutated. - Use
constassertions (as const) for literal types. - Use
satisfiesto check that an expression matches a type without widening it. - Use
as constfor enum‑like objects instead of enums when possible. - Use
NonNullableutility type to removenullandundefined. - Use
PickandOmitto create derived types. - Use
typeofto infer types from values. - Use
keyofto get union of keys from a type. - Use
@ts-expect-errorinstead of@ts-ignoreto document expected errors.
📌 Quick Reference
Check TypeScript version:
Compile:
Compile with watch:
Initialize tsconfig:
Run with ts‑node:
tsc --versionCompile:
tscCompile with watch:
tsc --watchInitialize tsconfig:
tsc --initRun with ts‑node:
npx ts-node file.ts