Using Coherent UI with TypeScript 0.9

by Dimitar Trendafilov July. 08, 13 0 Comment

Some time ago we showed how to use

.Now that TypeScript 0.9 is released  with new features such as generics, overloading on constants and declaration merging we can take much more advantage of its static type checking. First lets see what these features do and then see how it can be used with Coherent UI.
Overloading on constants is the most interesting of the three and is one of the unique features of TypeScript. It allows for precise type annotations on functions that return different objects based on the value of an argument. The definitive example is document.createElement:


This not only saves us the annoying cast in
 

But also catches the next typo at compile time if we are more a little bit more explicit about the type:


Declaration merging allows to split declaration of module or an interface in multiple files. Although it doesn’t sound very impressive, the other features would be less convenient to use with Coherent UI API without it.

Generics have no surprises and work as most other languages. They allow for type safe declaration of containers and generic functions. We are going to use them for type safe declaration of promises:


Combined with overloading on constants, generics give us ability to declare type safe events for Coherent UI. We can describe the number of arguments and their types for each event we expect:


As you already have noticed the same combination can be used for type safe declarations for the engine.call method.

Given the above declarations I would hope the following code to generate a compile-time error about Show having wrong signature:

Unfortunately not. As the TypeScript speficiation says in section 3.7.2.4: Specialized Signatures:
“Because string literal types are subtypes of the String primitive type, when a function call argument matches a parameter of a string literal type in a specialized signature, the overload resolution rules (section 4.12.1) give preference to that signature over a similar signature with a regular string parameter.” 
This means that if the second argument is not of a type matching the overload declaration, the declaration is simply ignored and the code is perfectly valid.

TypeScript gets better and better and is used in more projects. Most JavaScript libraries have type declarations either bundled or in projects like DefinitelyTyped, making TypeScript valuable even for smaller projects that just glue some third-party libraries.
So if want to use TypeScript for your game user interface the place to start is the type declarations for coherent.js

Follow Dimitar on Twitter: @DimitarNT

Social Shares

Leave a Comment