Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: How to add static methods to built-in classes

Is there anyhow anyway to add some static method to types like Date, String, Array, etc?

For example I want to add method today to Date class and in JavaScript I can simply add a property to it or maybe I use Object.defineProperty:

Date.today = function(){
    let date = new Date;
    date.setHours(0,0,0,0);
    return date;
}

Object.defineProperty(Date, 'today', { get() { ... }});

But I didn't find anyway to inform TypeScript about this new static member. Am I missing something or Did I google it the wrong way?

like image 564
Morteza Tourani Avatar asked Oct 10 '17 10:10

Morteza Tourani


People also ask

How do I create a static method in TypeScript?

To create a static function simply add the static keyword and call it directly from the class instead of calling it from the instance of the class.

Does TypeScript support static classes?

TypeScript doesn't allow a static property or method to be affected by an object instance. We can instantiate the object just fine, but if we try to access the property or method, TypeScript will raise an error.

How do you define a static property in TypeScript?

With TypeScript, we can designate members as instance variables, which don't have the keyword static before them, and static members, which have the keyword static keyword before them. Static members can be accessed without having the class instantiated.

How do you implement a static method?

Similar to Default Method in Interface, the static method in an interface can be defined in the interface, but cannot be overridden in Implementation Classes. To use a static method, Interface name should be instantiated with it, as it is a part of the Interface only.


2 Answers

You have to augment the DateConstructor interface to add static properties:

declare global {
    interface DateConstructor {
        today: () => Date
    }
}   

Date.today = function(){
    let date = new Date;
    date.setHours(0,0,0,0);
    return date;
}

Similarly extend StringConstructor and ArrayConstructor for string and arrays. See declaration merging.

like image 56
Saravana Avatar answered Oct 14 '22 18:10

Saravana


I use this code to extend Object with static method. export class ObjectExtensions { }

declare global {
    interface ObjectConstructor {
        safeGet<T>(expresstion: () => T, defaultValue: T): T;
    }
}

Object.safeGet = function <T>(expresstion: () => T, defaultValue: T): T {
    try {
        const value = expresstion();
        if (value != null) return value;

    } catch (e) {
    }
    return defaultValue;
}

In main.ts you have to call this class like this

new ObjectExtensions();

And then you can use it like this:

Object.safeGet<number>(() => data.property.numberProperty);
like image 22
Oleg Polezky Avatar answered Oct 14 '22 20:10

Oleg Polezky