Issue
Say I have two types of numbers that I'm tracking like latitude and longitude. I would like to represent these variables with the basic number primitive, but disallow assignment of a longitude to a latitude variable in typescript.
Is there a way to sub-class the number primitive so that typescript detects this assignment as illegal? Someway to coerce nominal typing so that this code fails?
var longitude : LongitudeNumber = new LongitudeNumber();
var latitude : LatitudeNumber;
latitude = longitude; // <-- type failure
The answer to "How to extend a primitive type in typescript?" seems like it will put me in the right direction, but I am not sure how to extend that solution to create distinct nominal sub-types for different kinds of numbers.
Do I have to wrapper the primitive? If so, can I make it behave somewhat seamlessly like a normal number or would I have to reference a sub-member? Can I just somehow create a typescript compile-time number subclass?
Solution
There isn't a way to do this.
A suggestion tracking this on the GitHub site is Units of Measure.
In a future release, you'll be able to use type to define alternate names for the primitives, but these will not have any checking associated with them:
type lat = number;
type lon = number;
var x: lat = 43;
var y: lon = 48;
y = 'hello'; // error
x = y; // No error
Answered By - Ryan Cavanaugh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.