John Mcfetridge
John Mcfetridge

Reputation: 1197

type inference causes code to fail

consider the following code:

var yum: HTMLElement;
  var bin: Element;
yum = document.createElement('p');
var y: Node = yum.cloneNode(true);
bin.appendChild(y);

y.style.display = 'none';     //fails Error 2   Cannot convert 'Node' to 'HTMLElement': Type 'Node' is missing property 'click' from type 'HTMLElement'

of course this fails as cloneName returns Node and not HTMLElement and if you try what to convert manually from Node to HTMLElement then the same error occurs. So I stuck as I do not see a way to change the opacity. Now this is javascript I was trying to move into Typescript.

Upvotes: 0

Views: 310

Answers (1)

Fenton
Fenton

Reputation: 250922

If you know that the element being cloned is an HTMLElement as in your example, you can cast it:

var yum: HTMLElement;
var bin: Element;

yum = document.createElement('p');
var y: HTMLElement = <HTMLElement> yum.cloneNode(true);
bin.appendChild(y);

y.style.display = 'none';

Where the type is explicit, you could opt not to annotate the types, like this:

var bin: Element;
var yum = document.createElement('p'); // type inferred as createElement returns an HTMLElement
var y = <HTMLElement> yum.cloneNode(true); // type inferred from the cast

bin.appendChild(y);
y.style.display = 'none'; 

Upvotes: 3

Related Questions