This project is read-only.

Type aliases, subclassing primitives

Topics: Language Specification
Oct 7, 2012 at 9:49 AM

Not sure if this is already possible, I'd like to be able to do this:

class degree extends number { 0..360 }

var rotation: degree;

For a more strong type-checking.



Oct 8, 2012 at 6:06 PM

Currently, types in TypeScript check conditions that can be checked at compile time and then are removed when the .js is output.  This includes using the <Foo>bar form, where you can annotate an expression with a type.  Even in this case, we don't insert a runtime cast, we just assume that you "know what you're doing".


Oct 9, 2012 at 4:03 PM
Edited Oct 9, 2012 at 4:05 PM

I was thinking it'd be great to be able to add "magic sugar" functions to class definitions, to help tsc compiler TypeChecker.

For example:

class degree {
 _assignableFrom(source:any) {
   return (typeof source === "number" ) && (source >= 0) && (source <= 360);

var a:degree = 120; // good

TypeChecker.sourceIsRelatableToTarget will try at compile-time to eval and call "_assignableFrom"  as a last chance, and if it returns true, it will not raise then ErrorReporter.incompatibleTypes  and will just emit plain javascript:
var a=120;


Oct 11, 2012 at 3:16 AM

The problem with this is that it could only be enforced on constants.  In the example "var a: degree = 120;", if the constant were instead the result of calling a function, we could not at compile time know whether that returns a value that is in range or not.  Since TypeScript does not emit any runtime checks, the "degree" constraint would then be defeated in most cases.