Is there anyhow anyway to add some static method to types like Date
, String
, Array
, etc?
For example I want to add method to
You have to augment the DateConstructor
interface to add static properties:
declare global {
interface DateConstructor {
today: () => Date
}
}
Date.today = function(){
let date = new Date;
date.setHours(0,0,0,0);
return date;
}
Similarly extend StringConstructor
and ArrayConstructor
for string and arrays. See declaration merging.
I use this code to extend Object with static method. export class ObjectExtensions { }
declare global {
interface ObjectConstructor {
safeGet<T>(expresstion: () => T, defaultValue: T): T;
}
}
Object.safeGet = function <T>(expresstion: () => T, defaultValue: T): T {
try {
const value = expresstion();
if (value != null) return value;
} catch (e) {
}
return defaultValue;
}
In main.ts you have to call this class like this
new ObjectExtensions();
And then you can use it like this:
Object.safeGet<number>(() => data.property.numberProperty);