basarat
basarat

Reputation: 276115

How do I add methods to Date, String, Array, Number Etc in 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 

Upvotes: 3

Views: 258

Answers (1)

basarat
basarat

Reputation: 276115

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.

Upvotes: 6

Related Questions