How to define static property in TypeScript interface

前端 未结 14 1167
你的背包
你的背包 2020-11-28 05:49

I just want to declare a static property in typescript interface? I have not found anywhere regarding this.

interface myInterface {
  static         


        
14条回答
  •  有刺的猬
    2020-11-28 06:18

    You can't define a static property on an interface in TypeScript.

    Say you wanted to change the Date object, rather than trying to add to the definitions of Date, you could wrap it, or simply create your rich date class to do the stuff that Date doesn't do.

    class RichDate {
        public static MinValue = new Date();
    }
    

    Because Date is an interface in TypeScript, you can't extend it with a class using the extends keyword, which is a bit of a shame as this would be a good solution if date was a class.

    If you want to extend the Date object to provide a MinValue property on the prototype, you can:

    interface Date {
        MinValue: Date;
    }
    
    Date.prototype.MinValue = new Date(0);
    

    Called using:

    var x = new Date();
    console.log(x.MinValue);
    

    And if you want to make it available without an instance, you also can... but it is a bit fussy.

    interface DateStatic extends Date {
        MinValue: Date;
    }
    
    Date['MinValue'] = new Date(0);
    

    Called using:

    var x: DateStatic = Date; // We aren't using an instance
    console.log(x.MinValue);
    

提交回复
热议问题