Extension Methods | Typescript
- Extension Methods | Typescript
Primeira forma
export const add = Symbol('add');
function addImpl(this: Date, dateOrMs: number | Date) {
return new Date(+this + +dateOrMs);
}
export const addDays = Symbol('addDays');
function addDaysImpl(this: Date, days: number) {
return this[add](days * 24 * 60 * 60 * 1000);
}
declare global {
export interface Date {
[add]: typeof addImpl;
[addDays]: typeof addDaysImpl;
}
}
Date.prototype[add] = addImpl;
Date.prototype[addDays] = addDaysImpl;
----------------------
//chamando a função
// mostra o import para adicionar
d[add](1).toISOString();
Segunda forma
export default {};
declare global {
interface String {
numerize(): number;
convertToSlug(): string;
}
}
String.prototype.numerize = function (toFixed: number | null = null): number {
let value = parseFloat(this);
value = isNaN(value) || !isFinite(value) ? 0 : value;
return toFixed ? parseFloat(value.toFixed(toFixed)) : value;
};
String.prototype.convertToSlug = function (): string {
let str = this;
if (!str) {
return '';
}
return str.replace(/ +/g, '-').toLowerCase();
};
--------------------------------
import 'arquivo_extension';
"texto".numerize();
- Esse precisa colocar o import manualmente