Sunday, July 24, 2016

Recognizing TypeScript's Jurisdictional Boundary

While I was exploring the current Angular 2 documentation regarding forms and form field validity, I caught myself wondering why the Angular code wouldn't block or complain about an attempt to assign an incorrect data type value to an object property.  Given the following TypeScript object:


export class Villain {
  id: number;
  name: string;
  age: number;
  dateOfBirth: Date;
}

...you could be forgiven if you thought, for a brief moment at least, that a user entering property values for a Villain via a form would experience an error of some kind if they tried to enter a non-number in the age form field,or a string value of "7/14/84" in the date of birth field.

But of course that wouldn't happen. TypeScript only enforces those types when it compiles the code, preventing programmers from using the wrong data type in the code. That type enforcement is not carried through to the resulting JavaScript.

This is hardly a revelation.  TypeScript is a tool for writing JavaScript: it doesn't alter the base behavior or functionality of JavaScript.  But I can see developers spending a few hours coding classes and service methods in TypeScript, then turning their attention to the code that interacts with the web UI and having to remind themselves that the type protection doesn't apply to user/UI actions that change the class property values.  In that area of the code, you have to enforce the data types with explicit code.

And it made me wonder if there should be a way to carry those data type restrictions on class properties down to the resulting JavaScript code by default.  Not sure how feasible that would be.  I would think you'd have to make each property a private property with getter/setter methods where the setter method would ensure the incoming value met the data type criteria.  But then how would a data type mistmatch be handled?  You probably wouldn't want to throw an error:  you'd want to record the attempt in some readable property.  Would you prevent the property from being set to an invalid value, or would you allow it and count on the developer to write code to inspect the object for validity issues before proceeding?  And how would you provide a mechanism for adding custom validations on top of the data type validations?

No matter how you went about it, you'd end up with an opinionated process for enforcing the data types that probably wouldn't work for everyone, which is probably why TypeScript doesn't do anything like that with the compiled JavaScript code.

No comments:

Post a Comment