Rajagopal 웃
Rajagopal 웃

Reputation: 8471

Extending the properties of existing objects like Date in TypeScript

I need to declare a static MinValue property in Date. My javascript code looks like,

Date.MinValue = new Date("someDate");

I have found similar questions with answers But, it's all about just adding a function not properties. And also those functions are not defined as static. So, that's not helpful for me.

referred links,

  1. Extending Array in TypeScript
  2. How does prototype extend on typescript?

Upvotes: 9

Views: 9517

Answers (1)

Fenton
Fenton

Reputation: 251112

I don't think you can extend Date to have an additional static property. You can extend its prototype as follows:

interface Date {
    min: Date;
}

Date.prototype.min = new Date();

var x = new Date();
alert(x.min.toString());

To do what you really want to do, you would actually have to make a change to lib.d.ts:

declare var Date: {
    new (): Date;
    new (value: number): Date;
    new (value: string): Date;
    new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date;
    (): string;
    prototype: Date;
    parse(s: string): number;
    UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number;
    now(): number;
    min: Date;
}

And perform the extension in pure JS, to be loaded in addition to your TypeScript generated JavaScript.

    Date.min = new Date();

Upvotes: 9

Related Questions