how do you add a property to an existing type in typescript?
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;
}
}
Intersection Type
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>[];
Union Type
You could use Union type:
class newDateClass {
readonly fullYearUTC: number;
}
Then use like this:
date: Date | newDateClass