Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending the properties of existing objects like Date in TypeScript

Tags:

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?
like image 692
Rajagopal 웃 Avatar asked Dec 19 '12 11:12

Rajagopal 웃


1 Answers

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();
like image 114
Fenton Avatar answered Oct 07 '22 11:10

Fenton