Extension Method in Typescript

Bibby Chung
my-coding-life
Published in
2 min readJan 30, 2018

--

Yesterday I saw the article ‘Extension Method’. There are three way to create extension methods. In my memory I know a way in typescript documentation. I got it here. So I write some examples to use it.

Extending global types

declare global {
interface String {
toAddPrefix(prefix: string): string;
}
interface Array<T> {
toAddPostfix(postFix: string): Array<T>;
}
}

String.prototype.toAddPrefix = function (prefixStr: string) {
return `${prefixStr}${this}`;
}

Array.prototype.toAddPostfix = function (postFixStr: string) {
var _self = this as Array<string>;
return _self.map(a => `${a}${postFixStr}`)
};

String.prototype.toAddPrefix = function (prefixStr: string) {
return `${prefixStr}${this}`;
}

Array.prototype.toAddPostfix = function (postFixStr: string) {
var _self = this as Array<string>;
return _self.map(a => `${a}${postFixStr}`)
};

let’s test it

import './extensions';const str0 = 'str';
const prefixStr = str0.toAddPrefix('prefix_');
console.log(prefixStr); //prefix_str

const arr = ['str'];
const postfixArr = arr.toAddPostfix('_postfix');
console.log(postfixArr); //[ 'str_postfix' ]

Extending third-party module

import * as moment from 'moment';
declare module 'moment' {
export interface Moment {
toTaiwaneseYear(): number;
}
}

(moment.fn as any).toTaiwaneseYear = function () {
const _self = this as moment.Moment;
return _self.year() - 1911;
}

let’s test it

import * as moment from 'moment';
import './extensions';
const m = moment();
console.log(m.toTaiwaneseYear()); //107

It’s so easy. Enjoy..

Reference:
https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#augmenting-globalmodule-scope-from-modules
https://blog.kevinyang.net/2017/07/03/angular-method-extension

--

--