3 ms·
TypeScript aims to make a type system that can model anything you can do in JS. Of course JS can modify its objects, at runtime, in literally any way imaginable
by com2kid 3y ago
TypeScript aims to make a type system that can model anything you can do in JS. Of course JS can modify its objects, at runtime, in literally any way imaginable, so the TS type system has to be Turing complete. Anything less powerful and you aren't going to be able to model what arbitrary JS code is doing.
My go to example being a function that takes in an object with a bunch of camel case parameterFields and makes them into snake case parameter_fields.
Easy peasy in TypeScript, You can say, in a generic fashion, "pass an object with camelCase field names, and return the same object but the field names are snake_case".
This is incredibly useful when adapting between different systems!
Traditional OO systems fall flat on their face attempting such feats.
- stevage 3y agoFunny, I actually wrote and maintain a library which, amongst other things, does almost the same thing as your contrived example, except it's camelCase to kebab-case. It's written in Flow though, because that was what I knew at the time.
- com2kid 3y ago> does almost the same thing as your contrived example Sadly, not contrived! Anyone using protocol buffers is actually familiar with this exact scenario. Not sure how the JS PB compiler handles things though, I never bothered to look under the covers. Here is a random sample I found of both the types and the conversion code. https://gist.github.com/alfrdmalr/faa012e421d9f7f60c3e6d2d32581157 https://gist.github.com/alfrdmalr/faa012e421d9f7f60c3e6d2d32...
- stevage 3y agoYeah, cool. In my case I didn't really get all the type stuff right - I was mostly using Flow to be able to generate documentation.
- simonbw 3y agoI thought I was pretty good at TypeScript, but I can't imagine how I would write that function. Would you mind sharing that?
- com2kid 3y agoSee my above reply https://gist.github.com/alfrdmalr/faa012e421d9f7f60c3e6d2d32581157 https://gist.github.com/alfrdmalr/faa012e421d9f7f60c3e6d2d32... IIRC in one of the "what's new announcements" from the TS team included sample code to do it as well. Edit: here is another example of doing it https://gist.github.com/kuroski/9a7ae8e5e5c9e22985364d1ddbf3389d https://gist.github.com/kuroski/9a7ae8e5e5c9e22985364d1ddbf3... And here is a medium article walking through the code step by step https://medium.com/@fullstack-shepherd/typescript-transforming-types-with-snake-case-keys-to-camelcase-keys-or-how-to-keep-busy-in-9d5f074d9bfa https://medium.com/@fullstack-shepherd/typescript-transformi...
- EdwardDiego 3y agoThat's horrifyingly awesome.
- sizediterable 3y agoI don't know if its aim is necessarily to model anything you can do in JS. At the moment, TypeScript has zero understanding of prototypal inheritance and there hasn't been any visible progress in that direction.