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.)
To add a property to an object in TypeScript, set the property as optional on the interface you assign to the object using a question mark. You can then add the property at a later point in time without getting a type error. Copied!
Syntax. var object_name = { key1: “value1”, //scalar value key2: “value”, key3: function() { //functions }, key4:[“content1”, “content2”] //collection }; As shown above, an object can contain scalar values, functions and structures like arrays and tuples.
To use the Object. assign() method in TypeScript, pass a target object as the first parameter to the method and one or more source objects, e.g. const result = Object. assign({}, obj1, obj2) . The method will copy the properties from the source objects to the target object.
Use the Partial utility type to make all of the properties in a type optional, e.g. const emp: Partial<Employee> = {}; . The Partial utility type constructs a new type with all properties of the provided type set to optional. Copied!
In typescript, If you want to add members, you can use an intersection type:
type DateWithNewMember <T> = Partial<T>
& { newMember: boolean }
Then use like this:
dates: DateWithNewMember<Date>[];
You could use Union type:
class newDateClass {
readonly fullYearUTC: number;
}
Then use like this:
date: Date | newDateClass
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With