Skip to content
English
On this page

TypeScript

Usage

Install

sh
npm install TypeScript

Run

sh
npx tsc

Run with a specific config

sh
npx tsc --project configs/my_tsconfig.json

Triple slash directives

Reference built-in types

ts
/// <reference lib="es2016.array.include" />

Reference other types

ts
/// <reference path="../my_types" />
ts
/// <reference types="jquery" />

AMD

ts
/// <amd-module name="Name" />
ts
/// <amd-dependency path="app/foo" name="foo" />

Compiler comments

Don’t check this file

ts
// @ts-nocheck

Check this file (JS)

ts
// @ts-check

Ignore the next line

ts
// @ts-ignore

Expect an error on the next line

ts
// @ts-expect-error

Operators

?? (nullish coalescing)

typescript
function getValue(val?: number): number | 'nil' {
  // Will return 'nil' if `val` is falsey (including 0)
  // return val || 'nil';

  // Will only return 'nil' if `val` is null or undefined
  return val ?? 'nil';
}

?. (optional chaining)

typescript
function countCaps(value?: string) {
  // The `value` expression be undefined if `value` is null or
  // undefined, or if the `match` call doesn't find anything.
  return value?.match(/[A-Z]/g)?.length ?? 0;
}

! (null assertion)

typescript
let value: string | undefined;

// ... Code that we're sure will initialize `value` ...

// Assert that `value` is defined
console.log(`value is ${value!.length} characters long`);

&&=

typescript
let a;
let b = 1;
 
// assign a value only if current value is truthy
 
a &&= 'default'; // a is still undefined
b &&=  5; // b is now 5

||=

typescript
let a;
let b = 1;
 
// assign a value only if current value is falsy
 
a ||= 'default'; // a is 'default' now
b ||=  5; // b is still 1

??=

typescript
let a;
let b = 0;
 
// assign a value only if current value is null or undefined
 
a ??= 'default'; // a is now 'default'
b ??=  5; // b is still 0

Basic types

TypeCode
UntypedUntyped
A string string
A number number
A true / false value boolean
A non-primitive valueobject
Uninitialized value undefined
Explicitly empty valuenull
Null or undefined (usually only used for function returns)void
A value that can never occurnever
A value with an unknown typeunknown

Object types

Object

typescript
{
   requiredStringVal: string;
   optionalNum?: number;
   readonly readOnlyBool: bool;

}

Object with arbitrary string properties (like a hashmap or dictionary)

ts
{ [key: string]: Type; }
{ [key: number]: Type; }

Literal types

ts
let direction: 'left' | 'right'; // String
let roll: 1 | 2 | 3 | 4 | 5 | 6; // Numeric

Arrays and tuples

Array of strings

string[]

or

Array<string>

Array of functions that return strings

ts
(() => string)[]
// or

{ (): string; }[]
// or

Array<() => string>

Basic tuples

ts
let myTuple: [ string, number, boolean? ];
myTuple = [ 'test', 42 ];

Variadic tuples

ts
type Numbers = [number, number];
type Strings = [string, string];
 
type NumbersAndStrings = [...Numbers, ...Strings]; 
// [number, number, string, string]

Named tuples

ts
type Vector2D = [x: number, y: number];
function createVector2d(...args: Vector2D) {} 
// function createVector2d(x: number, y: number): void

Functions

Function type

ts
(arg1: Type, argN: Type) => Type; 

// or

{ (arg1: Type, argN: Type): Type; }

Constructor

ts
new () => ConstructedType;

// or

{ new (): ConstructedType; }

Function type with optional param

ts
(arg1: Type, optional?: Type) => ReturnType

Function type with rest param

ts
(arg1: Type, ...allOtherArgs: Type[]) => ReturnType

Function type with static property

ts
{ (): Type; staticProp: Type; }

Default argument

ts
function fn(arg1 = 'default'): ReturnType {}

Arrow function

ts
(arg1: Type): ReturnType => { ...; return value; }

// or

(arg1: Type): ReturnType => value;

this typing

ts
function fn(this: Foo, arg1: string) {}

Overloads

ts
function conv(a: string): number;
function conv(a: number): string;
function conv(a: string | number): string | number {
    ...
}

Union and intersection types

Union

ts
let myUnionVariable: number | string;

Intersection

ts
let myIntersectionType: Foo & Bar;

Named types

Interface

ts
interface Child extends Parent, SomeClass {
    property: Type;
    optionalProp?: Type;
    optionalMethod?(arg1: Type): ReturnType;
}

Class

ts
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

ts
enum Options {
    FIRST,
    EXPLICIT = 1,
    BOOLEAN = Options.FIRST | Options.EXPLICIT,
    COMPUTED = getValue()
}

enum Colors {
    Red = "#FF0000",
    Green = "#00FF00",
    Blue = "#0000FF"
}

Type alias

ts
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

ts
<T>(items: T[], callback: (item: T) => T): T[]

Interface with multiple types

ts
interface Pair<T1, T2> {
    first: T1;
    second: T2;
}

Constrained type parameter

ts
<T extends ConstrainedType>(): T

Default type parameter

ts
<T = DefaultType>(): T

Constrained and default type parameter

ts
<T extends ConstrainedType = DefaultType>(): T

Generic tuples

ts
type Arr = readonly any[];
 
function concat<U extends Arr, V extends Arr>(a: U, b: V): 
[...U, ...V] { return [...a, ...b] }
 
const strictResult = concat([1, 2] as const, ['3', '4'] as const);
const relaxedResult = concat([1, 2], ['3', '4']);
 
// strictResult is of type [1, 2, '3', '4']
// relaxedResult is of type (string | number)[]

Index, mapped, and conditional types

Index type query (keyof)

ts
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

ts
type Stringify<T> = { [P in keyof T]: string; }
type Partial<T> = { [P in keyof T]?: T[P]; }

Conditional types

ts
type Swapper = <T extends number | string>
(value: T) => T extends number ? string : number;

is equivalent to

ts
(value: number) => string

if T is number, or

ts
(value: string) => number

if T is string

Conditional mapped types

ts
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

ts
Partial<{ x: number; y: number; z: number; }>

is equivalent to

ts
{ x?: number; y?: number; z?: number; }

Readonly

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

is equivalent to

ts
{
    readonly x: number;

    readonly y: number;

    readonly z: number;

}

Pick

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

is equivalent to

ts
{ x: number; y: number; }

Record

ts
Record<'x' | 'y' | 'z', number>

is equivalent to

ts
{ x: number; y: number; z: number; }

Exclude

ts
type Excluded = Exclude<string | number, string>;

is equivalent to

ts
number

Extract

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

is equivalent to

ts
string

NonNullable

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

is equivalent to

ts
string | number

ReturnType

ts
type ReturnValue = ReturnType<() => string>;

is equivalent to

ts
string

InstanceType

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

is equivalent to

ts
Renderer

Type guards

Type predicates

ts
function isThing(val: unknown): val is Thing {
    // return true if val is a Thing
}

if (isThing(value)) {
    // value is of type Thing
}

typeof

ts
declare value: string | number;
if (typeof value === "number") {
    // value is of type Number
} else {
    // value is a string
}

instanceof

ts
declare value: Date | Error;

if (value instanceof Date) {
    // value is a Date
} else {
    // value is an Error
}

in

ts
interface Dog { woof(): void; }
interface Cat { meow(): void; }

function speak(pet: Dog | Cat) {
    if ('woof' in pet) {
        pet.woof()
    } else {
        pet.meow()
    }
}

Assertions

Type

ts
let val = someValue as string;
//or
let val = <string>someValue;

Const (immutable value)

ts
let point = { x: 20, y: 30 } as const;
// or
let point = <const>{ x: 20, y: 30 };

Ambient declarations

Global

ts
declare const $: JQueryStatic;

Module

ts
declare module "foo" {
    export class Bar { ... }
}

Wildcard module

ts
declare module "text!*" {
    const value: string;
    export default value;
}