Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  137] [ 5]  / answers: 1 / hits: 40433  / 12 Years ago, sun, december 16, 2012, 12:00:00

Possible Duplicate:

How does prototype extend on typescript?






I am currently learning TypeScript, and would like to know how it is possible to add functionality to existing objects. Say I want to add an implementation for Foo to the String object. In JavaScript I would do this:



String.prototype.Foo = function() {
// DO THIS...
}


Understanding that TypeScript classes, interfaces and modules are open ended led me to try the following, without success



1. Reference the JavaScript implementation from TypeScript



    JavaScript:

String.prototype.Foo = function() {
// DO THIS...
}

TypeScript:

var x = Hello World;
x.Foo(); //ERROR, Method does not exist


2. Extend the interface



interface String {
Foo(): number;
}

var x = Hello World;
x.Foo(); //Exists but no implementation.


3. Extend the class



class String {
Foo(): number {
return 0;
}
}

// ERROR: Duplicate identifier 'String'


As you can see from these results, so far I have been able to add the method via an interface contract, but no implementation, so, how do I go about defining AND implementing my Foo method as part of the pre-existing String class?


More From » typescript

 Answers
2

I have found the solution. It takes a combination of the interface and the JavaScript implementation. The interface provides the contract for TypeScript, allowing visibility of the new method. The JavaScript implementation provides the code that will be executed when the method is called.



Example:



interface String {
foo(): number;
}

String.prototype.foo= function() {
return 0;
}


As of TypeScript 1.4 you can now also extend static members:



interface StringConstructor {
bar(msg: string): void;
}

String.bar = function(msg: string) {
console.log(Example of static extension: + msg);
}

[#81393] Friday, December 14, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mackennamelissac

Total Points: 110
Total Questions: 118
Total Answers: 103

Location: Sweden
Member since Sun, Jan 16, 2022
2 Years ago
mackennamelissac questions
Thu, Jun 3, 21, 00:00, 3 Years ago
Tue, Mar 23, 21, 00:00, 3 Years ago
Sun, Dec 27, 20, 00:00, 3 Years ago
;