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

前端 未结 2 1980
孤独总比滥情好
孤独总比滥情好 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:25

    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.

提交回复
热议问题