Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add methods to Date, String, Array, Number Etc in TypeScript

Tags:

typescript

How do I tell TypeScript of additions to native types like Date,Number,String etc?

E.g. I want the following to compile (example from http://sugarjs.com/dates):

var date: Date = Date.create('tomorrow'); // I get a compile error
date.isAfter('March 1st') // I get a compile error 
like image 706
basarat Avatar asked Jun 07 '26 23:06

basarat


1 Answers

There are two kinds of extensions needed here.

1.) Static members addition to native types

e.g. create in the given example.

This can be done by adding to <type>Constructor interfaces. e.g.

interface DateConstructor {
    create(query: string): Date;
}

2.) Instance member additions to native types

e.g. isAfter in the given example.

This can be done by adding to <type> interface e.g.

interface Date {
    isAfter(query: string): boolean;
}

Complete example

interface DateConstructor {
    create(query: string): Date;
}
interface Date {
    isAfter(query: string): boolean;
}

var date: Date = Date.create('tomorrow'); // okay
date.isAfter('March 1st') // okay 

This has been possible since TypeScript 1.4.

like image 63
basarat Avatar answered Jun 10 '26 19:06

basarat