Suggestion: Create explicit cast syntax

Topics: Language Specification
Oct 18, 2012 at 8:01 PM

Look at this example:

/// <reference path="lib.d.ts"/> 

var cvElem: HTMLCanvasElement;

// This line throws an error because
// document.createElement()'s specified return type is Element
cvElem = document.createElement("canvas");

In this case, document.createElement() is really returning a HTMLCanvasElement object.

Because the compiler cannot know that, it will throw an error!
So here's my suggestion/idea for solving that problem:

Implement a special syntax for type casting/disabling compiler errors where the compiler would think you're using incompatible types. I'd go for something like this:

// C style
cvElem = (HTMLCanvasElement) document.createElement("canvas");

// C++ style
cvElem = explicit_cast<document.createElement("canvas")>;

// Just an idea spreading off my mind...
// Note the exclamation mark at the end!
cvElem = document.createElement("canvas")!;
Oct 18, 2012 at 8:18 PM

/// <reference path="lib.d.ts"/> 

var cvElem: HTMLCanvasElement;

// This line throws an error because
// document.createElement()'s specified return type is Element
cvElem = <HTMLCanvasElement>document.createElement("canvas");

Try that

Coordinator
Oct 19, 2012 at 3:52 PM

Like jmelgaard suggests, there are two different common ways of handling this.  In your case, you want to go from a type that is less specific (Element) to one that is more specific (HTMLCanvasElement).  In TypeScript, the way to generally do this is to use the type annotation "var x = <type>expression" instead of "var x: type".

var cvElem = <HTMLCanvasElement>document.createElement("canvas");

 

 

Oct 21, 2012 at 6:21 PM

Excellent, thanks for your solutions and explanation (@jonturner)!