Search code examples
typescript

How to define static property in TypeScript interface


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

interface myInterface {
  static Name:string;
}

Is it possible?


Solution

  • 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 = <any>Date; // We aren't using an instance
    console.log(x.MinValue);