TypeScript Cheatsheet



This TypeScript cheatsheet provides a concise reference to key TypeScript concepts, including types, functions, interfaces, and classes. It covers advanced topics such as generics, decorators, and type compatibility, with practical code examples for each feature. It is designed to help developers quickly understand and apply TypeScript's type system and object-oriented programming principles. Use this guide as a fast resource for writing efficient and type-safe code in TypeScript. 

Table of Contents

About

TypeScript is a language extension to JavaScript, which uses static types. It advances development vigor by implementing type safety, advocating computability of larger JavaScript applications, and eliminating certain errors at compile time, instead of run time.

Basic Types

Common primitive types such as boolean, number, and string. These are the building blocks of a TypeScript application.

boolean, number, string: Common primitive types. 

null, undefined: Absence of a value.

bigint, symbol: Special types for larger integers and unique values.

Any, Void, and Others

Special types such as any, void, and others that handle specific use cases in TypeScript.

any: Disables type-checking for the variable.

void: Represents no value (typically for functions that dont return anything).

Arrays and Tuples

Working with ordered collections of data like arrays and tuples.

Arrays: Use type[] or Array<type>.

Tuples: Define ordered sets of types, e.g., [string, number].

Union and Intersection Types

Union and intersection types to handle multiple possible types or combine multiple types.

Union Types: string | null | undefined.

Intersection Types: Combines multiple types into one.

Special Types

Specialized types such as never, unknown, and enum to handle unique cases.

never: Indicates unreachable code. 

unknown: A safer alternative to any.

enum: Allows creation of named constants. 

Enums

Enums allow for creating named constants, either numeric or string-based.

TypeDescriptionCode Example
Numeric EnumAutomatically assigned numeric values.

enum Direction { Up = 1, Down, Left, Right }

String Enum

Explicitly assign string values.

enum Status { Success = 'SUCCESS', Error = 'ERROR' }

Type Guards

Techniques for narrowing down types during runtime.

TypeDescriptionCode Example
typeof GuardChecks the type of a variable.

function print(value: string | number) { ... }

instanceof

Check if an object is an instance.

if (date instanceof Date) { ... }

Custom Guard

Function that returns value is Type.

function isString(value: unknown): value is string { ... }

Discriminated Unions

Using discriminated unions to narrow types based on a shared property.

DescriptionCode Example
Discriminant Property for Narrowing

type Shape = { kind: 'circle', radius: number }

Mapped Types

Mapped types allow you to transform the properties of a type.

Mapped TypeDescriptionCode Example
Partial<T>Makes all properties optional.

type PartialUser = Partial<{ name: string; age: number }>

Required<T>

Makes all properties required.

type RequiredUser = Required<PartialUser>

Readonly<T>

Makes all properties read-only.

type ReadonlyUser = Readonly<{ name: string; age: number }>

Utility Types

Utility types provide common transformations to work with types.

Utility TypeDescriptionCode Example
Pick<T, K>Selects specific keys from a type.

type NameOnly = Pick<User, 'name'>

Omit<T, K>

Excludes specific keys from a type.

type NoName = Omit<User, 'name'>

Record<K, T>

Creates an object type with keys.

type Dictionary = Record<string, number>

Extract<T, U>

Extracts types from T assignable to U.

type Extracted = Extract<'a' | 'b', 'a'>

Exclude<T, U>

Excludes types from T assignable to U.

type Excluded = Exclude<'a' | 'b', 'a'>

Never Type

The never type represents values that will never occur. It is used in cases like function signatures that never return or infinite loops.

DescriptionCode Example
Unreachable Code:
function fail(message: string): never { throw new Error(message); }
Exhaustiveness Check:
function check(value: 'a' | 'b') { ... }

Declarations

Declarations define variables, functions, classes, and other entities in TypeScript.

Variables: Variables are used to store data and can be assigned types explicitly or inferred automatically.

let isDone: boolean; let isDone: boolean = false; 

Functions: Functions in TypeScript can be typed to ensure parameters and return values are consistent.

function add(a: number, b: number): number { return a + b; }

Type Assertions: Type assertions are used to tell the compiler to treat a value as a specific type.

let len: number = (input as string).length;

Interfaces

Interfaces are used to define the shape of an object, specifying which properties and methods it must have.

Inline Interfaces: Define interfaces directly within the function parameter for simple structures.

function printLabel(options: { label: string }) { ... }

Explicit Interfaces: Declare a separate interface to specify the structure of the parameter object.

interface LabelOptions { label: string; }

Optional Properties: Define properties that are not required in an interface, using the "?" symbol.

interface User { name: string; age?: number; }

Read-only Properties: Define properties that cannot be modified after being initialized, using the read-only keyword.

interface User { readonly name: string; }

Dynamic Keys: Use index signatures to define object keys that can be dynamically assigned.

{ [key: string]: Object[] }

Type Aliases

Type aliases are used to create new names for types, including unions, intersections, and other complex types.

Aliases: Combine multiple types or data structures under a single alias.

type Name = string | string[];

Intersections: Combine multiple types into one by requiring all properties of both.

type ColorfulCircle = Colorful & Circle;

Function Types

Function types define the signature of a function, including the types of the parameters and return values.

function getUser(callback: (user: User) => any) { callback({...}); }

Classes

Classes in TypeScript are used to define objects with properties and methods.

Basic Structure: Define a class with a constructor and instance properties.

class Point { x: number; y: number; static instances = 0; constructor(x: number, y: number) { this.x = x; this.y = y; } } 

Inheritance: Extend a class to inherit its properties and methods.

class Point3D extends Point { ... }

Generics

Generics: Generics allow you to write reusable and type-safe code by allowing types to be passed as parameters.

class Greeter<T> { greeting: T; constructor(message: T) { this.greeting = message; } } 

Modules

Modules: Modules allow you to organize your code into reusable pieces. They can export functions, objects, and variables and import them into other files.

export interface User { ... }

Advanced Types

Advanced types in TypeScript include conditional types, infer types and template literal types.

Type Extraction: Extract specific types from existing types.

type Walls = Building['room']['walls'];

Keyof Type Operator: Create a type that consists of all keys of an object type.

type P = keyof Point; // x | y

Conditional Types: Define types based on conditions using extends.

type ToArray<T> = T extends any ? T[] : never;

Inferring Types: Extract return types from functions using conditional types.

type GetReturnType<T> = T extends (...args: unknown[]) => infer R ? R : never;

Literal Types

Literal Types: Literal types allow you to specify exact values for a variable or parameter instead of a broader type.

const literalPoint = { x: 4, y: 2 } as const;

Template Literal Types: Decorators are special functions that can modify classes, methods, or properties. They are often used in frameworks like Angular.

type TrimLeft<S extends string> = S extends `${SpaceChar}${infer Rest}` ? TrimLeft<Rest> : S;

Decorators

The table given below explains the types of decorators along with examples:

TypeDescriptionCode Example
Class DecoratorAdds metadata to a class.

function Logger(target: Function) { ... } @Logger class MyClass {}

Property Decorator

Adds metadata to class properties.

function Readonly(target: any, key: string) { ... } class User { @Readonly name = 'John'; }

Type Compatibility and Structural Typing

Type Compatibility and Structural TypingExplanationCode Example
Structural TypingA type is compatible if it has the same structure.

type Point = { x: number; y: number; }; type Coordinate = { x: number; y: number; }; const point: Point = { x: 10, y: 20 }; const coordinate: Coordinate = point; // Compatible

Function CompatibilityFunction parameters are checked structurally.

type Callback = (a: number, b: number) => number; const add: Callback = (x, y) => x + y; function executeCallback(cb: Callback, a: number, b: number): number { return cb(a, b); } executeCallback(add, 5, 10);

Advertisements
close