Close

TypeScript - Standard JavaScript's built-in objects Support

[Updated: Jun 12, 2019, Created: Jun 11, 2019]

Various JavaScript's built-in objects are supported in TypeScript.

The lib.<xyz>.d.ts files are used to provide typescript type information about JavaScript's built-in objects.

To have some idea how these types are defined, we will go through some of them.

JavaScript Date object

JavaScript Date object can be used in TypeScript as:

let d: Date = new Date();
let y: number = d.getFullYear();
console.log(y);

Output

2019

The interfaces for types Date and DateConstructor (used to create new instance of Date) are defined in lib.es5.d.ts as:

interface Date {
    toString(): string;
    toDateString(): string;
    toTimeString(): string;
    toLocaleString(): string;
    toLocaleDateString(): string;
    toLocaleTimeString(): string;
    valueOf(): number;
    getTime(): number;
    getFullYear(): number;
    getUTCFullYear(): number;
    getMonth(): number;
    getUTCMonth(): number;
    getDate(): number;
    getUTCDate(): number;
    getDay(): number;
    getUTCDay(): number;
    getHours(): number;
    getUTCHours(): number;
    getMinutes(): number;
    getUTCMinutes(): number;
    getSeconds(): number;
    getUTCSeconds(): number;
    getMilliseconds(): number;
    getUTCMilliseconds(): number;
    getTimezoneOffset(): number;
    setTime(time: number): number;
    setMilliseconds(ms: number): number;
    setUTCMilliseconds(ms: number): number;
    setSeconds(sec: number, ms?: number): number;
    setUTCSeconds(sec: number, ms?: number): number;
    setMinutes(min: number, sec?: number, ms?: number): number;
    setUTCMinutes(min: number, sec?: number, ms?: number): number;
    setHours(hours: number, min?: number, sec?: number, ms?: number): number;
    setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number;
    setDate(date: number): number;
    setUTCDate(date: number): number;
    setMonth(month: number, date?: number): number;
    setUTCMonth(month: number, date?: number): number;
    setFullYear(year: number, month?: number, date?: number): number;
    setUTCFullYear(year: number, month?: number, date?: number): number;
    toUTCString(): string;
    toISOString(): string;
    toJSON(key?: any): string;
}

interface DateConstructor {
    new(): Date;
    new(value: number | string): Date;
    new(year: number, month: number, date?: number, hours?: number, minutes?: number, 
                                                                    seconds?: number, ms?: number): Date;
    (): string;
    readonly prototype: Date;
    parse(s: string): number;
    UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, 
                                                                    seconds?: number, ms?: number): number;
    now(): number;
}

JavaScript Math object

let p: number = Math.pow(3,4);
console.log(p);
let s: number = Math.sqrt(18);
console.log(s);

Output

81
4.242640687119285

The JavaScript Math is also defined in lib.es5.d.ts

interface Math {
    readonly E: number;
    readonly LN10: number;
    readonly LN2: number;
    readonly LOG2E: number;
    readonly LOG10E: number;
    readonly PI: number;
    readonly SQRT1_2: number;
    readonly SQRT2: number;
    abs(x: number): number;
    acos(x: number): number;
    asin(x: number): number;
    atan(x: number): number;
    atan2(y: number, x: number): number;
    ceil(x: number): number;
    cos(x: number): number;
    exp(x: number): number;
    floor(x: number): number;
    log(x: number): number;
    max(...values: number[]): number;
    min(...values: number[]): number;
    pow(x: number, y: number): number;
    random(): number;
    round(x: number): number;
    sin(x: number): number;
    sqrt(x: number): number;
    tan(x: number): number;
}

JavaScript Collections

JavaScript collections Map, Set, WeakMap and WeakSet are also supported by TypeScript.

let m: Map<number,string> = new Map<number,string>();
m.set(1, "one");
console.log(m);

let st: Set<number> = new Set<number>();
st.add(1);
st.add(3);
console.log(st);

Output

Map { 1 => 'one' }
Set { 1, 3 }

The types for these collections are defined in lib.es2015.collection.d.ts

interface Map<K, V> {
    clear(): void;
    delete(key: K): boolean;
    forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void;
    get(key: K): V | undefined;
    has(key: K): boolean;
    set(key: K, value: V): this;
    readonly size: number;
}

interface MapConstructor {
    new(): Map<any, any>;
    new<K, V>(entries?: ReadonlyArray<[K, V]> | null): Map<K, V>;
    readonly prototype: Map<any, any>;
}
....
interface ReadonlyMap<K, V> {
    forEach(callbackfn: (value: V, key: K, map: ReadonlyMap<K, V>) => void, thisArg?: any): void;
    get(key: K): V | undefined;
    has(key: K): boolean;
    readonly size: number;
}

interface WeakMap<K extends object, V> {
    delete(key: K): boolean;
    get(key: K): V | undefined;
    has(key: K): boolean;
    set(key: K, value: V): this;
}

interface WeakMapConstructor {
    new <K extends object = object, V = any>(entries?: ReadonlyArray<[K, V]> | null): WeakMap<K, V>;
    readonly prototype: WeakMap<object, any>;
}
declare var WeakMap: WeakMapConstructor;

interface Set<T> {
    add(value: T): this;
    clear(): void;
    delete(value: T): boolean;
    forEach(callbackfn: (value: T, value2: T, set: Set<T>) => void, thisArg?: any): void;
    has(value: T): boolean;
    readonly size: number;
}

interface SetConstructor {
    new <T = any>(values?: ReadonlyArray<T> | null): Set<T>;
    readonly prototype: Set<any>;
}
declare var Set: SetConstructor;

interface ReadonlySet<T> {
    forEach(callbackfn: (value: T, value2: T, set: ReadonlySet<T>) => void, thisArg?: any): void;
    has(value: T): boolean;
    readonly size: number;
}

interface WeakSet<T extends object> {
    add(value: T): this;
    delete(value: T): boolean;
    has(value: T): boolean;
}

interface WeakSetConstructor {
    new <T extends object = object>(values?: ReadonlyArray<T> | null): WeakSet<T>;
    readonly prototype: WeakSet<object>;
}
declare var WeakSet: WeakSetConstructor;

As seen above, TypeScript defines ReadonlyMap and ReadonlySet which are read only variant of Map and Set.

Following example shows how to use ReadonlySet:

function createReadOnlySet<T>(...e: T[]): ReadonlySet<T> {
    let s: Set<T> = new Set();
    e.forEach((value: T, index: number) => {
        s.add(value)
    });
    return s;
}

let rs: ReadonlySet<number> = createReadOnlySet<number>(1, 3, 5);
console.log(rs.entries());
console.log(rs.has(5));

Output

[Set Iterator] { 1, 3, 5 }
true

JavaScript Promise

let promise: Promise<number> = new Promise<number>(function (resolve, reject) {
    console.log('promise executor function is called');
    setTimeout(function () { //just add some delay
        if (Math.random() > 0.2) {
            resolve(100);
        } else {
            reject("Got error")
        }
    }, 3000);
});

console.log('-- calling then --');
promise.then(
    function (result: number) {
        console.log("success result: " + result);
    },
    function (error: any) {
        console.log("error: " + error)
    });
console.log('-- after then --');
promise executor function is called
-- calling then --
-- after then --
success result: 100

See also JavaScript Promise tutorial.

The types related to Promise are defined in lib.es2015.promise.d.ts and lib.es5.d.ts.

lib.es2015.promise.d.ts:

interface PromiseConstructor {
    readonly prototype: Promise<any>;
    new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, 
                                  reject: (reason?: any) => void) => void): Promise<T>;
    all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | 
                      PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | 
                      PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | 
                      PromiseLike<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
    ........
    race<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | 
                      PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | 
                      PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | 
                      PromiseLike<T10>]): Promise<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9 | T10>;
    ........
    reject<T = never>(reason?: any): Promise<T>;
    ....
    resolve<T>(value: T | PromiseLike<T>): Promise<T>;
    resolve(): Promise<void>;
}

declare var Promise: PromiseConstructor;

lib.es5.d.ts:

 .................
declare type PromiseConstructorLike = new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) => PromiseLike<T>;

interface PromiseLike<T> {
    then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
}

interface Promise<T> {
    then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
    catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}
..................

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.5.1
JavaScript's object type support in TypeScript Select All Download
  • typescript-javascript-built-in-objects
    • Ex1Date.ts

    See Also