TypeScript Cheat Sheet

TypeScript Cheat Sheet

This cheat sheet is an adjunct to our Definitive TypeScript Guide.

Originally published Nov 6, 2018. Last updated on April 10, 2020 for: TypeScript 3.8

Usage
Install
npm install TypeScript
Run
npx tsc
Run with a specific config
npx tsc --project configs/my_tsconfig.json
Triple slash directives
Reference built-in types
/// <reference lib="es2016.array.include" />
Reference other types
/// <reference path="../my_types" />
/// <reference types="jquery" />
AMD
/// <amd-module name="Name" />
/// <amd-dependency path="app/foo" name="foo" />
Compiler comments
Don’t check this file
// @ts-nocheck
Check this file (JS)
// @ts-check
Ignore the next line
// @ts-ignore
Basic types
Untyped
any
A string
string
A number
number
A true / false value
boolean
A non-primitive value
object
Uninitialized value
undefined
Explicitly empty value
null
Null or undefined (usually only used for function returns)
void
A value that can never occur
never
A value with an unknown type
unknown
Object types
Object
{
    requiredStringVal: string;
    optionalNum?: number;
    readonly readOnlyBool: bool;

}
Object with arbitrary string properties (like a hashmap or dictionary)
{ [key: string]: Type; }
{ [key: number]: Type; }
Literal types
String
let direction: 'left' | 'right';
Numeric
let roll: 1 | 2 | 3 | 4 | 5 | 6;
Arrays and tuples
Array of strings
string[]

or

Array<string>
Array of functions that return strings
(() => string)[]

or

{ (): string; }[]

or

Array<() => string>
Basic tuples
let myTuple: [ string, number, boolean? ];
myTuple = [ 'test', 42 ];
Functions
Function type
(arg1: Type, argN: Type) => Type;

or

{ (arg1: Type, argN: Type): Type; }
Constructor
new () => ConstructedType;

or

{ new (): ConstructedType; }
Function type with optional param
(arg1: Type, optional?: Type) => ReturnType
Function type with rest param
(arg1: Type, ...allOtherArgs: Type[]) => ReturnType
Function type with static property
{ (): Type; staticProp: Type; }
Default argument
function fn(arg1 = 'default'): ReturnType {}
Arrow function
(arg1: Type): ReturnType => { ...; return value; }

or

(arg1: Type): ReturnType => value;
this typing
function fn(this: Foo, arg1: string) {}
Overloads
function conv(a: string): number;
function conv(a: number): string;
function conv(a: string | number): string | number {
    ...
}
Union and intersection types
Union
let myUnionVariable: number | string;
Intersection
let myIntersectionType: Foo & Bar;
Named types
Interface
interface Child extends Parent, SomeClass {
    property: Type;
    optionalProp?: Type;
    optionalMethod?(arg1: Type): ReturnType;
}
Class
class Child
extends Parent

implements Child, OtherChild {
    property: Type;
    defaultProperty = 'default value';
    private _privateProperty: Type;
    private readonly _privateReadonlyProperty: Type;
    static staticProperty: Type;
    constructor(arg1: Type) {
        super(arg1);
    }

    private _privateMethod(): Type {}

    methodProperty: (arg1: Type) => ReturnType;
    overloadedMethod(arg1: Type): ReturnType;
    overloadedMethod(arg1: OtherType): ReturnType;
    overloadedMethod(arg1: CommonT): CommonReturnT {}
    static staticMethod(): ReturnType {}
    subclassedMethod(arg1: Type): ReturnType {
        super.subclassedMethod(arg1);
    }
}
Enum
enum Options {
    FIRST,
    EXPLICIT = 1,
    BOOLEAN = Options.FIRST | Options.EXPLICIT,
    COMPUTED = getValue()
}

enum Colors {
    Red = "#FF0000",
    Green = "#00FF00",
    Blue = "#0000FF"
}
Type alias
    type Name = string;

    type Direction = 'left' | 'right';

    type ElementCreator = (type: string) => Element;

    type Point = { x: number, y: number };

    type Point3D = Point & { z: number };

    type PointProp = keyof Point; // 'x' | 'y'

    const point: Point = { x: 1, y: 2 };

    type PtValProp = keyof typeof point; // 'x' | 'y'
Generics
Function using type parameters
<T>(items: T[], callback: (item: T) => T): T[]
Interface with multiple types
interface Pair<T1, T2> {
    first: T1;
    second: T2;
}
Constrained type parameter
<T extends ConstrainedType>(): T
Default type parameter
<T = DefaultType>(): T
Constrained and default type parameter
<T extends ConstrainedType = DefaultType>(): T
Index, mapped, and conditional types
Index type query (keyof)
type Point = { x: number, y: number };
let pointProp: keyof Point = 'x';

function getProp<T, K extends keyof T>(
    val: T,
    propName: K

): T[K] { ... }
Mapped types
type Stringify<T> = { [P in keyof T]: string; }
type Partial<T> = { [P in keyof T]?: T[P]; }
Conditional types
type Swapper = <T extends number | string>
    (value: T) => T extends number ? string : number;

is equivalent to

(value: number) => string

if T is number, or

(value: string) => number

if T is string

Conditional mapped types
interface Person {
    firstName: string;
    lastName: string;
    age: number;
}

type StringProps<T> = {
    [K in keyof T]: T[K] extends string ? K : never;
};

type PersonStrings = StringProps<Person>;

// PersonStrings is "firstName" | "lastName"
Utility types
Partial
Partial<{ x: number; y: number; z: number; }>

is equivalent to

{ x?: number; y?: number; z?: number; }
Readonly
Readonly<{ x: number; y: number; z: number; }>

is equivalent to

{
    readonly x: number;

    readonly y: number;

    readonly z: number;

}
Pick
Pick<{ x: number; y: number; z: number; }, 'x' | 'y'>

is equivalent to

{ x: number; y: number; }
Record
Record<'x' | 'y' | 'z', number>

is equivalent to

{ x: number; y: number; z: number; }
Exclude
type Excluded = Exclude<string | number, string>;

is equivalent to

number
Extract
type Extracted = Extract<string | number, string>;

is equivalent to

string
NonNullable
type NonNull = NonNullable<string | number | void>;

is equivalent to

string | number
ReturnType
type ReturnValue = ReturnType<() => string>;

is equivalent to

string
InstanceType
class Renderer() {}
type Instance = InstanceType<typeof Renderer>;

is equivalent to

Renderer
Type guards
Type predicates
function isThing(val: unknown): val is Thing {
    // return true if val is a Thing
}

if (isThing(value)) {
    // value is of type Thing
}
Typeof
declare value: string | number;
if (typeof value === "number") {
    // value is of type Number
} else {
    // value is a string
}
Instanceof
declare value: Date | Error;

if (value instanceof Date) {
    // value is a Date

} else {
    // value is an Error
}
Assertions
Type
let val = someValue as string;

or

let val = <string>someValue;
Const (immutable value)
let point = { x: 20, y: 30 } as const;

or

let point = <const>{ x: 20, y: 30 };
Ambient declarations
Global
declare const $: JQueryStatic;
Module
declare module "foo" {
    export class Bar { ... }
}
Wildcard module
declare module "text!*" {
    const value: string;
    export default value;
}

Is this cheat sheet missing anything? Let us know.

Learn more about how SitePen can be your partner.

SitePen is a strategic consultancy committed to achieving technical objectives, solving critical business problems and helping our customers build web applications the right way, the first time.
Share This