Spongman
Spongman

Reputation: 9861

how do you add a property to an existing type in typescript?

I'm trying to add a property to the javascript 'Date' prototype.

in javascript, i'd just do this:

Object.defineProperty(Date.prototype, "fullYearUTC", {
    get: function () { return this.getUTCFullYear(); },
    enumerable: true,
    configurable: true
});

I thought I'd just be able to do the following in typescript:

class Date
{
    get fullYearUTC(): number { return this.getUTCFullYear() }
}

but I get the error

Cannot redeclare block-scoped variable 'Date'.

why doesn't this work?

(please no comments on whether or not you think doing this is a good idea. this question is not about that.)

Upvotes: 51

Views: 93300

Answers (2)

Sukhminder Sandhu
Sukhminder Sandhu

Reputation: 875

Intersection Type

In typescript, If you want to add members, you can use an intersection type:

type DateWithNewMember = T & { newMember: boolean }

Where T is the type you want to add member to.

Then use like this:

dates: DateWithNewMember<Date>[];

Union Type

You could use Union type:

class newDateClass {
   readonly fullYearUTC: number;
}

Then use like this:

date: Date | newDateClass

Upvotes: 70

Nitzan Tomer
Nitzan Tomer

Reputation: 164129

You can not create a class named Date, you can have your own date object which extends it:

class MyDate extends Date {
    get fullYearUTC(): number {
        return this.getUTCFullYear();
    }
}

But if you want to modify the existing Date you need to keep doing what you did with your javascript code.
As for adding it to the ts type, you need to use it as an interface:

interface Date {
    readonly fullYearUTC: number;
}

Or you can augment the global namespace:

declare global {
    interface Date {
        readonly fullYearUTC: number;
    }
}

Upvotes: 16

Related Questions