Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
45
rated 0 times [  46] [ 1]  / answers: 1 / hits: 28879  / 9 Years ago, sun, july 5, 2015, 12:00:00

I need to add a member to an HTMLElement, in other words, I need to store data into an element. This is what I would like to achieve as if I am coding in ScriptSharp.



/** My method */
public DoIt(element: Element, obj: Object) {
Literal({0}.extended = {1}, element, obj); // This is not standard Typescript!
}


In my example ScriptSharp (a project to convert C# code into Javascript) provides a Script.Literal object that allows developers to write plain Javascript when a C# abstraction is not possible.



So that the Javascript output is:



// Probably Typescript will render it a bit differently, but basically
// this is what we get in the end...
var _doit = function(element, obj) {
element.extended = obj;
};


How can I achieve this in Typescript? Or maybe I should handle this problem in a different way?


More From » typescript

 Answers
9

Any valid JavaScript is also valid TypeScript.
This means that you can write literal JS in any place in your code.



var _doit = function(element, obj) {
element.extended = obj;
};


This is valid JS and TS.



However, since you use TypeScript, you may also want to use static typing with your code.
If you just add types to your code, it will compile correctly, but you'll get a semantic error:



var _doit = function(element:HTMLElement, obj) {
element.extended = obj; // error: HTMLElement doesn't have property 'extended'
};


To prevent this error, you can notify the compiler that you intend to create a new property on HTMLElement:



interface HTMLElement {
extended?: any;
}


Now the compiler knows that you have an (optional) property extended on HTMLElement and will compile without errors. You will also get code autocompletion on this property (and JSDoc if provided).


[#65924] Thursday, July 2, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jameson

Total Points: 534
Total Questions: 103
Total Answers: 102

Location: Lithuania
Member since Fri, Sep 4, 2020
4 Years ago
jameson questions
;