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

前端 未结 2 1961
孤独总比滥情好
孤独总比滥情好 2021-02-15 12:56

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

For example I want to add method to

2条回答
  •  逝去的感伤
    2021-02-15 13:30

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

    declare global {
        interface ObjectConstructor {
            safeGet(expresstion: () => T, defaultValue: T): T;
        }
    }
    
    Object.safeGet = function (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(() => data.property.numberProperty);
    

提交回复
热议问题