Skip to content

TypeScript Quick Reference

A quick lookup for TypeScript concepts and syntax grouped by category. All examples assume TypeScript 5+ with strict mode enabled.

TypeExamplesNotes
string'hello', "world"Text
number42, 3.14, -1All numbers (int and float)
booleantrue, false
nullnullExplicit absence of value
undefinedundefinedUninitialized variable
bigint100nLarge integers
symbolSymbol('id')Unique identifiers

// Variable
let name: string = 'Alice';
let count: number = 0;
let isActive: boolean = true;
// Function parameters and return type
function greet(name: string): string {
return `Hello, ${name}`;
}
// Arrow function
const add = (a: number, b: number): number => a + b;
// No return value
function log(msg: string): void {
console.log(msg);
}
// Function that never returns
function fail(msg: string): never {
throw new Error(msg);
}

// Arrays
let names: string[] = ['Alice', 'Bob'];
let scores: Array<number> = [95, 87, 100];
// Readonly array
const ids: readonly number[] = [1, 2, 3];
// Tuple — fixed length, specific types at each position
let point: [number, number] = [10, 20];
let entry: [string, number] = ['score', 100];
// Optional tuple element
let pair: [string, number?] = ['alone'];

interface User {
id: number;
name: string;
email?: string; // optional property
readonly createdAt: Date; // cannot be reassigned after creation
}
// Extending an interface
interface Admin extends User {
role: 'admin' | 'superadmin';
permissions: string[];
}
// Function type in interface
interface Formatter {
format(value: number): string;
}
// Index signature — any number of properties with string keys
interface Dictionary {
[key: string]: string;
}

// Object shape (similar to interface)
type Point = {
x: number;
y: number;
};
// Union type
type Status = 'pending' | 'active' | 'closed';
type ID = string | number;
// Intersection type — combines multiple types
type AdminUser = User & { role: string };
// Function type
type Callback = (error: Error | null, result?: string) => void;
// Conditional type
type IsString<T> = T extends string ? true : false;

Interface vs type alias: Use interface for object shapes that may be extended. Use type for unions, intersections, primitives, and computed types.


// String literals
type Direction = 'north' | 'south' | 'east' | 'west';
type Theme = 'light' | 'dark';
// Number literals
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
// Boolean literal
type AlwaysTrue = true;
// Template literal type
type EventName = `on${string}`; // matches 'onClick', 'onChange', etc.

// Numeric enum (default — values auto-increment from 0)
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right, // 3
}
// String enum (preferred — values are readable at runtime)
enum Status {
Pending = 'PENDING',
Active = 'ACTIVE',
Closed = 'CLOSED',
}
const current: Status = Status.Active;
console.log(current); // 'ACTIVE'

// Generic function
function identity<T>(value: T): T {
return value;
}
identity<string>('hello');
identity(42); // TypeScript infers T = number
// Generic with constraint
function getLength<T extends { length: number }>(value: T): number {
return value.length;
}
getLength('hello'); // 5
getLength([1, 2, 3]); // 3
// Generic interface
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
// Using it
type UserResponse = ApiResponse<User>;
type ListResponse = ApiResponse<User[]>;
// Generic class
class Stack<T> {
private items: T[] = [];
push(item: T): void { this.items.push(item); }
pop(): T | undefined { return this.items.pop(); }
}
const stack = new Stack<number>();
stack.push(1);

// typeof guard
function processInput(input: string | number) {
if (typeof input === 'string') {
return input.toUpperCase(); // TypeScript knows it's a string here
}
return input.toFixed(2); // TypeScript knows it's a number here
}
// instanceof guard
function handleError(error: unknown) {
if (error instanceof Error) {
console.log(error.message); // Error properties available
}
}
// in operator guard
interface Dog { bark(): void; }
interface Cat { meow(): void; }
function makeSound(animal: Dog | Cat) {
if ('bark' in animal) {
animal.bark();
} else {
animal.meow();
}
}
// Truthiness guard
function printName(name: string | null) {
if (name) {
console.log(name.toUpperCase()); // name is string here
}
}
// Discriminated union
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; side: number };
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle': return Math.PI * shape.radius ** 2;
case 'square': return shape.side ** 2;
}
}
// Type predicate
function isString(value: unknown): value is string {
return typeof value === 'string';
}

UtilityWhat it doesExample
Partial<T>All properties optionalPartial<User>
Required<T>All properties requiredRequired<User>
Readonly<T>All properties readonlyReadonly<User>
Pick<T, K>Keep only listed keysPick<User, 'id' | 'name'>
Omit<T, K>Exclude listed keysOmit<User, 'password'>
Record<K, V>Object with key type K and value type VRecord<string, number>
Exclude<T, U>Remove types from unionExclude<Status, 'closed'>
Extract<T, U>Keep only types in unionExtract<string | number, string>
NonNullable<T>Remove null and undefinedNonNullable<string | null>
ReturnType<T>Return type of a functionReturnType<typeof greet>
Parameters<T>Parameter types as tupleParameters<typeof greet>
// Examples
type UserPreview = Pick<User, 'id' | 'name'>;
type SafeUser = Omit<User, 'password' | 'secret'>;
type UpdateUser = Partial<Pick<User, 'name' | 'email'>>;
type Scores = Record<string, number>;

class Animal {
// Access modifiers
public name: string;
private age: number;
protected species: string;
readonly id: string;
constructor(name: string, age: number, species: string) {
this.name = name;
this.age = age;
this.species = species;
this.id = crypto.randomUUID();
}
// Getter
get info(): string {
return `${this.name} (${this.species})`;
}
// Static method
static create(name: string): Animal {
return new Animal(name, 0, 'unknown');
}
}
// Extending
class Dog extends Animal {
breed: string;
constructor(name: string, breed: string) {
super(name, 2, 'Canis lupus');
this.breed = breed;
}
bark(): void {
console.log(`${this.name} says woof!`);
}
}
// Shorthand parameter properties
class Point {
constructor(
public x: number,
public y: number,
private label: string = 'point'
) {}
}
ModifierAccessible from
publicAnywhere (default)
privateOnly inside this class
protectedInside this class and subclasses
readonlyRead anywhere, set only in constructor

// Selecting elements
const btn = document.querySelector<HTMLButtonElement>('#submit');
const input = document.querySelector<HTMLInputElement>('.search');
const items = document.querySelectorAll<HTMLLIElement>('.item');
// Type assertion
const canvas = document.getElementById('myCanvas') as HTMLCanvasElement;
// Null checks required with strict mode
btn?.addEventListener('click', handleClick); // optional chaining
input!.value; // non-null assertion (use sparingly)
if (btn) {
btn.textContent = 'Submitted'; // narrowed to HTMLButtonElement
}
// Event types
function handleClick(e: MouseEvent): void { ... }
function handleInput(e: InputEvent): void {
const target = e.target as HTMLInputElement;
console.log(target.value);
}
function handleSubmit(e: SubmitEvent): void {
e.preventDefault();
}
function handleKey(e: KeyboardEvent): void {
if (e.key === 'Enter') { ... }
}

TypeMeaning
anyOpts out of type checking — avoid
unknownType-safe alternative to any — must narrow before use
neverA value that can never occur (exhaustive checks, throwing functions)
voidFunction returns nothing meaningful
objectAny non-primitive value
// unknown — must check before use
function parse(input: unknown): string {
if (typeof input === 'string') return input;
if (typeof input === 'number') return input.toString();
throw new Error('Unsupported type');
}
// never — exhaustive switch check
function assertNever(x: never): never {
throw new Error('Unexpected value: ' + x);
}

{
"compilerOptions": {
"target": "ES2020", // output JavaScript version
"module": "ESNext", // module system
"strict": true, // enables all strict checks
"noImplicitAny": true, // error on implicit any
"strictNullChecks": true, // null/undefined must be handled explicitly
"outDir": "./dist", // compiled output directory
"rootDir": "./src", // source files root
"esModuleInterop": true, // better CommonJS/ESModule interop
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true // skip type checking of .d.ts files
}
}