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

孤者浪人 提交于 2021-01-21 04:18:29

问题


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?


回答1:


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.




回答2:


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);


来源:https://stackoverflow.com/questions/46664732/typescript-how-to-add-static-methods-to-built-in-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!