Declaring an HTMLElement Typescript

typescript htmlelement
access html element in typescript angular
typescript getelementbyid value
typescript dom
typescript types
typescript dom types
typescript create htmlelement
string to htmlelement typescript

In the default TypeScript HTML app from visual studio, I added

HTMLElement 

to the first line of the window.onload event handler, thinking that I could provide a type for "el".

thus:

class Greeter {
    element: HTMLElement;
    span: HTMLElement;
    timerToken: number;

    constructor (element: HTMLElement) { 
        this.element = element;
        this.element.innerText += "The time is: ";
        this.span = document.createElement('span');
        this.element.appendChild(this.span);
        this.span.innerText = new Date().toUTCString();
    }

    start() {
        this.timerToken = setInterval(() => this.span.innerText = new Date().toUTCString(), 500);
    }

    stop() {
        clearTimeout(this.timerToken);
    }

}

window.onload = () => {
    HTMLElement el = document.getElementById('content');
    var greeter = new Greeter(el);
    greeter.start();
};

I get an error

Compile Error. See error list for details .../app.ts (25,17): Expected ';'

Any clue why? I suspect I am missing something obvious.

The type comes after the name in TypeScript, partly because types are optional.

So your line:

HTMLElement el = document.getElementById('content');

Needs to change to:

const el: HTMLElement = document.getElementById('content');

Back in 2013, the type HTMLElement would have been inferred from the return value of getElementById, this is still the case if you aren't using strict null checks (but you ought to be using the strict modes in TypeScript). If you are enforcing strict null checks you will find the return type of getElementById has changed from HTMLElement to HTMLElement | null. The change makes the type more correct, because you don't always find an element.

So when using type mode, you will be encouraged by the compiler to use a type assertion to ensure you found an element. Like this:

const el: HTMLElement | null = document.getElementById('content');

if (el) {
  const definitelyAnElement: HTMLElement = el;
}

I have included the types to demonstrate what happens when you run the code. The interesting bit is that el has the narrower type HTMLElement within the if statement, due to you eliminating the possibility of it being null.

You can do exactly the same thing, with the same resulting types, without any type annotations. They will be inferred by the compiler, thus saving all that extra typing:

const el = document.getElementById('content');

if (el) {
  const definitelyAnElement = el;
}

Handbook - DOM Manipulation, The type comes after the name in TypeScript, partly because types are optional. So your line: HTMLElement el = document.getElementById('content');. Needs to  TypeScript’s type inference will take care of it and only if you had some nasty code, e.g. that assigns different type of values to the same variable, you can have a problem. If refactoring that

Okay: weird syntax!

var el: HTMLElement = document.getElementById('content');

fixes the problem. I wonder why the example didn't do this in the first place?

complete code:

class Greeter {
    element: HTMLElement;
    span: HTMLElement;
    timerToken: number;

    constructor (element: HTMLElement) { 
        this.element = element;
        this.element.innerText += "The time is: ";
        this.span = document.createElement('span');
        this.element.appendChild(this.span);
        this.span.innerText = new Date().toUTCString();
    }

    start() {
        this.timerToken = setInterval(() => this.span.innerText = new Date().toUTCString(), 500);
    }

    stop() {
        clearTimeout(this.timerToken);
    }

}

window.onload = () => {
    var el: HTMLElement = document.getElementById('content');
    var greeter = new Greeter(el);
    greeter.start();
};

HTMLElement, Type declaration. constructor: function. new __type(): Element. Defined in node_modules/typedoc/node_modules/typescript/lib/lib.dom.d.ts:5354. Returns  The way that works, is to cast the element to an HTMLElement. let nodes: NodeListOf<HTMLElement> = document.querySelectorAll('a') as NodeListOf<HTMLElement>;

In JavaScript you declare variables or functions by using the keywords var, let or function. In TypeScript classes you declare class members or methods without these keywords followed by a colon and the type or interface of that class member.

It’s just syntax sugar, there is no difference between:

var el: HTMLElement = document.getElementById('content');

and:

var el = document.getElementById('content');

On the other hand, because you specify the type you get all the information of your HTMLElement object.

Learning TypeScript: Hello world with DOM manipulation, It's about how to do DOM manipulation in TypeScript and how they are not available in the language tutorials. Typescript type declaration HTMLElement type is just a common interface for all the html elements but the  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more How to avoid typescript error: Property 'innerHTML' does not exist on type 'Element'

Note that const declarations are block-scoped.

const el: HTMLElement | null = document.getElementById('content');

if (el) {
  const definitelyAnElement: HTMLElement = el;
}

So the value of definitelyAnElement is not accessible outside of the {}.

(I would have commented above, but I do not have enough Reputation apparently.)

TypeScript, More and less known ways to improve your TypeScript code method's typing and maps specific string literals (like "div", "table" or "input") to corresponding HTML element types: interface Here is the improved declaration: In TypeScript, we support much the same types as you would expect in JavaScript, with a convenient enumeration type thrown in to help things along. Boolean # The most basic datatype is the simple true/false value, which JavaScript and TypeScript call a boolean value.

HTMLElement, Defined in ypedoc/node_modules/typescript/bin/lib.d.ts:2706; Defined in public getElementsByTagName(name: ""article""): NodeListOf<HTMLElement>. Also if you want to use an interface with new, that can't be the export (as it is a type) you need to declare a const and export that: declare module 'mypackageid' { interface MyClassCtor { new (div: HTMLElement, conf: any) : {}; } const MyClass : MyClassCtor; export = MyClass; }

HTMLElement, The HTMLElement interface represents any HTML element. Some elements directly implement this interface, while others implement it via an  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more TypeScript variable that is a typed function

Lesson 01: Introduction to TypeScript, The data type of these elements is named HTMLElement. Based on this, the formula to declare a variable for an HTML element is: var | let | const variable-​name;. Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question. Provide details and share your research! But avoid … Asking for help, clarification, or responding to other answers. Making statements based on opinion; back them up with references or personal experience. To learn more, see our tips on writing great

Comments
  • let el: HTMLElement or let el: Node
  • Thanks. I do like adding the type even if it can be inferred though! I am glad both are supported.
  • In my experience it returns HTMLElement | null which is not comparable to HTMLElement in typescript. So unless processing stops here this is not the whole story
  • Hi @Clarence - yes, this changed since 2013, so I'll some additional information around that.
  • The declaration of the element must be: const el = document.getElementById('content') as HTMLElement;
  • @Orici - I disagree. The type returned from getElementById is HTMLElement or with strict null checks HTMLElement | null. In either case, allowing the el variable to have an inferred type is the path to success, as per the last example in the answer.
  • I was using Visual Studio 2010 or 2013 at the time, I think. It has been a while :)
  • Is there really a HTMLElement type in TypeScript?!
  • There is an HTMLElement interface in TypeScript. It has no runtime effect.