DEV Community

Cover image for A use case for TypeScript Generics

A use case for TypeScript Generics

Julian Garamendy on August 15, 2019

The following may be a bit obvious for some. But something just clicked in my head and I thought I'd write it down. When generics are a g...
Collapse
 
stealthmusic profile image
Jan Wedel • Edited

Great write up, thanks! I’m recently doing more and more typescript (coming from Java) and it’s sometimes confusing to get things right. Although I would also use a type it’s pretty handy for tests to use objects as types as you’ve shown.

The one thing that bugs me the most about the TS type system is the type erasure at runtime. I’ve had some bugs where while debugging I had a string in a variable of type int...

Collapse
 
juliang profile image
Julian Garamendy

Hi Jan, Thank you for reading and commenting.

Having a string on a variable of type number is unfortunately possible because there's no TypeScript at runtime; only JavaScript.

If your TS configuration is strict this should not be normally possible, unless of course, you're loading and parsing external data at runtime, which is very common.

For instance, you expect an object's id to be of type number but the JSON response from the server has it as a string.

One way to avoid this is to validate the server response at runtime. You can do this using something like ts.data.json or io-ts

Here's an article on dev.to showing how to use ts.data.json

Collapse
 
stealthmusic profile image
Jan Wedel

In my case, it was an input element that was bound to the component in Angular. The types were correct, but the form returned strings...

Thread Thread
 
juliang profile image
Julian Garamendy

Ah. I'm afraid I don't have enough experience with Angular. I suppose there are other reasons for that miss-type to happen: a library could be exporting the wrong types.

Thread Thread
 
stealthmusic profile image
Jan Wedel

You can see it in the dom, that all form values are strings in the browser. There are no types. When you bin an integer to a form input, it will be a string eventually. When the user modifies it, the new string goes back to the model.

I really wish there were some statically typed version of TS that would be compiled to WebASM... maybe that would be a way to circumvent the JS quirks at runtime.

Collapse
 
jonlauridsen profile image
Jon Lauridsen

Nice example 👍