snippettypescriptMajorCanonical
How to define static property in TypeScript interface
Viewed 0 times
propertytypescripthowinterfacestaticdefine
Problem
I just want to declare a static property in typescript interface? I have not found anywhere regarding this.
Is it possible?
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
Because Date is an interface in TypeScript, you can't extend it with a class using the
If you want to extend the Date object to provide a
Called using:
And if you want to make it available without an instance, you also can... but it is a bit fussy.
Called using:
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);Code Snippets
class RichDate {
public static MinValue = new Date();
}interface Date {
MinValue: Date;
}
Date.prototype.MinValue = new Date(0);var x = new Date();
console.log(x.MinValue);interface DateStatic extends Date {
MinValue: Date;
}
Date['MinValue'] = new Date(0);var x: DateStatic = <any>Date; // We aren't using an instance
console.log(x.MinValue);Context
Stack Overflow Q#13955157, score: 70
Revisions (0)
No revisions yet.