154 points · by mrbbk · 6y ago · 186 comments
Coupling your front end and back end in this way can give you false confidence in making API changes. If you control both sides of the API on a web app that doesn't have too many users yet, then this can be very productive, but consider this situation:
You've made a breaking API change on the back end, and thanks to your type system, you make the corresponding front end changes as well, which is great. You deploy your code, and the back end changes take effect immediately. Visitors who were in the middle of a session are still running the old front end code, and their requests start failing. Cached copies of the front end start failing too.
You can engineer around this but it's better to have a system that doesn't make introducing breaking API changes too easy. It should be painful.
If your want to change from A to B, your first deploy is deploying B without stopping A from working. It could be a totally new endpoint, or you could just throw a version field into the request body or querystring. Once everyone has switched off of A, you can remove it from your codebase so only B remains without actually affecting anyone's session.
If you don't want to pollute all your querystrings or request bodies with version fields, you could have an optional newVersion boolean field that only needs to appear during a switchover or make a temporary endpoint for updated clients to hit instead of the old endpoint:
# state at start
/foo <- uses API A
# deploy new endpoint
/foo <- uses API A
/foo/new <- uses API B
# wait for everyone to swtich to /foo/new, then deploy API to /foo, removing support for API A (this could be split into two deploys if you wanted)
/foo <- uses API B
/foo/new <- uses API B
# wait for everyone to switch over to /foo, then remove /foo/new
/foo <- uses API BIMHO that's an easier solution than having to implement a backward compatible API or other API versioning solutions.
I’m curious if anyone has a system for managing this that they love. I’ve pretty much only seen painful ways.
It's not perfect (I've ignored the comments before, thinking I knew better... I didn't), but it seems to help.
It wouldn't be difficult to make it more sophisticated, and then completely block PRs it knew weren't backward compatible, but we haven't seen a strong need to do that yet.
Right, just version the API, or have the app refresh itself when appropriate. Isn't this a fairly straightforward issue to address?
Also, as BiteCode_dev points out, this issue has nothing to do with whether you use a static type system.
I second the sentiment though. I wouldn't choose to use plain JavaScript over TypeScript for any significant project.
You might ask why I wouldn't just use a more fully typed language like Java. My main response is that I love having the flexibility to choose how strict the types should be. Sometimes, typing something out fully is not worth the trouble. Having escape hatches lets me make that choice. While I enjoy using types to turn runtime bugs into compile time errors as much as possible, it's not the right thing to do 100% of the time.
What is an example of this in your experience? I am trying to think of one, but after 25 years of programming, I cannot say I have ever encountered a case where it was worth using ‘an escape hatch’ that did not bite us later on. Maybe it is the type of software/clients I work with, but ‘the trouble’ is not really something I have seem before I think.
It was definitely worth the effort then. I also recognize why it is a very unlikely scenario to repeat.
The other place where I used dynamic most heavily in C# was that it was really great for IronPython interop where you could have a bit of "data science" done in a Python module, build that to a .NET assembly and call into the Python module from C#. (Though the other direction was more common, using IronPython to do data science around a bulk of C# models and code.) With so much more data science since that past life of mine having moved to Python, it's almost a shame that IronPython hasn't really kept up.
Maybe I should have amended my comments for 99% of the time? Or perhaps that there are other functionalities (e.g. tuple types, reflection) to to make working with types almost as easy as without? I use reflection very frequently...
I saw other commenter say that the benefit of using TS in the frontend and backend, then DB updates in the backend also update the frontend code: "The beauty of Gary’s setup is changes to his database update the types for the server side Code AND client side code. The value of that comes from using the same language in both platforms"
Can you get this sort of benefit with Kotlin? How?
https://www.newtonsoft.com/json/help/html/SerializationAttri...
I would avoid using dynamic (I believe underneath it is basically the same as the Dictionary<T, U> anyway, howeve r I don't really care to look it up).
Also regarding var. It is best IMO to use var when evident i.e. If the var right hand side is obvious what the type is use var, if it isn't use the Type name.
e.g.
When you should use var (it is evident from the right hand side)
var name = "Joe Bloggs";
vs when it isn't evident: var myVariables = _service.SomeMethod();
It allows the code to be better read without the IDE. However obviously it is up to you.A change to the DB schema just required me to refresh our edmx from the DB schema and then build.
But type safety is a spectrum anyway. One could say that not having dependent types is like having a swimming pool without a lifeguard.
Should every swimming pool in the world have a lifeguard? Probably not.
It advertises lots of benefits but the enforced schema types are worth the price of admission even if you're doing simple CRUD with no graphs.
TypeScript does provide a lot of benefits, but for it to truly succeed and take over in the JS world would mean it has to truly also reflect, and enable JS's functional and dynamic roots. JS got where it is by being JS.. an extremely flexible and accommodating language. HTML got this far today by doing the same, just google XHTML if you doubt that. So for TypeScript to succeed where CoffeeScript failed, this may be the direction it needs to lean more towards: being less divisive, and inviting all kinds of programming paradigms to the party.
That, after-all is how JS succeeded.
JS got where it is solely by being the language built into browsers.
All of these were at one point or another "built into the browser", but where are they now? Give credit where it is due, the success of the web as a platform lies not in its technical superiority over alternatives, but in its inclusiveness and flexibility. Any tech that is trying to replace HTML, CSS and JS in this regards will seriously have to consider and accommodate this, or suffer the same fate of hundreds of other pretenders to the throne. Long live the king! Long live open, approachable and flexible tech!
Exhibit A: List of very different and diverse languages that compile to JS ( https://github.com/jashkenas/coffeescript/wiki/List-of-langu... ). If this does not demonstrate the flexibility and malleability of the language, then I do not know what does. Take web assembly for example, which has been around for over five years now, and was specifically designed as a "compile to" language. How many languages compile to web assembly in comparison?
Any tech that is as divisive as TS is simply not going to get far. Flash ActionScript was massive 10 years ago compared to any alternative to JS tech today, and where is it now? The creator of TS even quotes ActionScript as one of the main inspirations for TS. ActionScript even had a more powerful version of Reacts JSX (ES4), where is it today? CoffeeScript was all the rage 5 years ago, JS simply absorbed all its good ideas, where is it today? The things that last, that stand the test of time are the things that are flexible and accommodate different ways of doing things. For your beloved TS to stand the test of time, it has got to accommodate the whole JS eco-system, not just those who favor the static object oriented way of doing things.
As an example, I can write a React+Redux app in TS, and be writing 100% plain functions (components + reducers) the entire way through.
From my viewpoint, TS has more than hit enough critical mass to survive for the long term:
- Microsoft is heavily invested in its ongoing development
- The Angular community requires use of TS
- The React community has split in general between types and no types, but a recent survey of /r/reactjs readers indicated ~50% of React devs are using TS [0]
- Where CoffeeScript introduced new syntax entirely, TS's focus on being a superset of standardized JS means that there's both less to worry about compat-wise _and_ it can be seen as a way to use new language features instead of Babel
FWIW, I wrote up my thoughts on learning and using TS as both an app dev and a Redux maintainer [1], and I'm sold on using going forward.
[0] https://www.swyx.io/writing/react-survey-2019/
[1] https://blog.isquaredsoftware.com/2019/11/blogged-answers-le...
VB was never built into all browsers. As far as Flash and Java applets, they were popular until they stopped being supported in all browsers - namely the iPhone and iPad.
Exhibit A: List of very different and diverse languages that compile to JS ( https://github.com/jashkenas/coffeescript/wiki/List-of-langu.... ). If this does not demonstrate the flexibility and malleability of the language, then I do not know what does.
Almost any language can be transpiled into any other language. That says nothing about any trait inherent in the language.
Flash ActionScript was massive 10 years ago compared to any alternative to JS tech today, and where is it now?
Apple singlehandedly killed Flash by not supporting it on iOS.
CoffeeScript was all the rage 5 years ago, JS simply absorbed all its good ideas, where is it today?
CoffeeScript was never championed by a company that has the revenue and clout that MS has and never got the adoption. Please don’t mention all of the initiatives that Google tried. Google isn’t exactly known for its ability to manage a platform.
If you want to validate data coming over IO then your options are data validation libraries such joi, io-ts, and yup. You have to write seperate data validators on top of your types. io-ts has a way of deriving types from validators, but io-ts is often seen as quite intimidating being built on top of fp-ts.
No matter how carefully you maintain strict typing within your typscript project the moment you hit IO everything is basically `any`.
Some projects like openapi-generator might generate some validators for server respones, but I've not seen any good generators that do actual validation.
I'm not sure if apollo-graphql does responses validation? Does anyone know?
io-ts is pretty scary, though. I like the `runtypes` library but it doesn't help me express my types in a way clients can consume, which, enh.
Caveat, I've only been using it for two weeks.
Since in my current job I can’t use graphql but have to type everything in openapi, Had to resort to writing my own lib to get to the same functionality for a REST backend in TS - https://github.com/ovotech/laminar
https://github.com/moltar/typescript-runtime-type-benchmarks
It is a bit of a pain to setup, but once it is done, I've found that it works pretty well.
First transform the JSON into proper class-objects and then validate the object for correctnes.
IMHO this has nothing to do with TypeScript because in your runtime all the type information is gone and you need to validate the remote data never the less. TypeScript can help you structure your validations but you need to write them.
For me, the duplicated types turned out to be less of a hassle than initially anticipated. In many cases, I ended up with different data structures anyway because the data is transformed in the client. I think of them as transport types and client types.
was expecting JS -> TS
/opinion
You shouldn't be so quick to assume that everyone else is clueless.
> With the Ruby backend, we sometimes forgot that a particular API property held an array of strings, not a single string. ... These are normal dynamic language problems in any system whose tests don't have 100% test coverage.
TDD in general focuses on code-adjacent test strategies like unit tests. In the Ruby TDD world it's a popular strategy to test first, code second at the level of classes or even individual methods. In practice this"tests = code = tests" philosophy produces both more code and a focus on metrics like coverage that only measure "for how much of my code do I have other code that asserts that my code is doing what the other code says it should be doing" rather than ensuring "my code is actually doing what someone else needs it to do".
"Testing" as I intend the term means using the software to do whatever it is supposed to. For a server side API that probably means consume it via a client. Any client that relies on the type of a property being an array instead of a string will blow up (except perhaps Python, grr). Any reasonably complete smoke or integration testing regime should expose this problem, but more immediately I think developers should be actively testing the thing they are changing while they are changing it. Personally I dislike compilers and restrictive type systems in large part because they _inhibit_ this sort of rapid, iterative testing and fixing. Partially functional dynamically typed code is far more useful to me as I work through a series of related changes than statically typed code that requires I fix all the issues it perceives as important before I can keep going on what really matters.
But that's not without cost. At least in the Ruby world (and Bernhardt holds/held this view) integrated tests are to be avoided where possible because it creates a negative feedback loop of slow tests and an exponential number of tests that need to be written to achieve equivalent coverage.
> but more immediately I think developers should be actively testing the thing they are changing while they are changing it
This smells like the age-old discipline/rigour/professionalism platitude often trotted out by proponents of Software Craftsmanship. I'd rather embrace the fact that humans make mistakes and optimise for that, rather than hold people to unreasonable standards.
Furthermore, while I agree that people should be testing the thing they are changing while they are changing it, you appear to be implying that only one form of testing is acceptable here. Why not test the type signature? Why not a formal proof of correctness? Why not a property-based test? There are many ways to improve the chances of a piece of software to work. Restricting ourselves to only one of those ways is, quite frankly, dumb.
> Personally I dislike compilers and restrictive type systems in large part because they _inhibit_ this sort of rapid, iterative testing and fixing.
That's a fine opinion to have, but that's all it is. I've worked professionally with dynamic languages, and I hold the opposite view. I work with a few projects totalling about 60,000 lines of Haskell, and I feel the language enables rapid, iterative testing much more than Ruby ever did for me. Of course I can't prove this empirically, which is why my opinion will only ever be as good as yours, and vice versa.
> Partially functional dynamically typed code is far more useful to me as I work through a series of related changes than statically typed code that requires I fix all the issues it perceives as important before I can keep going on what really matters.
I'm sorry, but this is plainly incorrect. The ability to defer type errors to runtime certainly exists in Haskell, and I expect not exclusively.
I am currently also working on a project written in a JS backend that's slowly porting to TS, for the same reasons, but I still would prefer to go back to C# and take it a level further. I just don't enjoy the TypeScript language all that much.
You say this sarcastically, but every JS-related thread on HN turns into a flamewar between type lovers and haters.
The type haters make exactly the argument you're mocking: that typeless languages do not result in more type errors. Their reasoning is along the lines of, "I don't need a type system because I'm a professional and don't make mistakes."
That sounds laughable or like an exaggeration, but it's a surprisingly common line of thinking. The buggiest code I ever worked on was a PHP code base written by someone who had been coding for 20 years and had a Master's in CS. Before I inherited the code, he told me, "I code in the terminal. I don't need IDE features because I don't really make mistakes in PHP anymore."
Again, seems satirical, but not uncommon.
This argument will never be resolved because it's dominated by psychological factors. Once you've adapted to environment A, A's costs (e.g. hoops the compiler makes you jump through / time spent tracking down type errors) become habitual and you don't notice them anymore. Meanwhile the costs of unfamiliar environment B are extremely highlighted in your attention. Similarly, if you like and identify with A, its benefits will be top-of-mind for you, while if you don't like B (and nobody likes B), you'll discount its benefits.
It gets worse. Sometimes benefits are costs until you make it through a learning curve. An example is parentheses in Lisp. They stick out like a sore thumb until one day they don't. Later you realize that they were a liberating force all along, and you now have anti-gravity powers you never dreamt of. (<-- This is an example of how people talk when they are adapted to an environment whose costs they no longer count and whose benefits are top-of-mind for them.) We can't even agree on what the costs and benefits are, let alone how to measure them.
It's no wonder that people feel so strongly about this dispute. When you don't count the costs of your preferred environment, and only count the benefits, it gets obvious pretty quickly that other people are idiots. For some reason the idiots feel the opposite and perversely insist on it.
It gets worse. Imagine that you're a decent, fairminded sort and so, magnanimously as is your wont, you decide to give the idiots a fair shake—you know, just to verify that you're being fair and whatnot. You fire up whatever it is (Clojure? OCaml? needless to say, you make a charitable choice) and start programming for a while. What happens? All the costs of unfamiliarity hit you in the face. Not one of the benefits that has lived at the top of your mind for years is anywhere to be seen. This thing doesn't even catch trivial type errors at compile time! / I can't even execute this bit of code in a REPL! This is a painful experience. It can even be an enraging one, for example if you are forced for some extraneous reason to work on a system you didn't create using tools you don't like. Most people who go through that experience once have their views solidified for life. Meanwhile someone else had the opposite experience.
Given how passionately people feel about this and the certainty in forum threads about it, it's curious (or maybe to be expected) that the question of published evidence comes up so rarely. HN user luu did the definitive survey on this: https://danluu.com/empirical-pl/. The short version is that such studies as there are don't address the core question and/or find insignificant effects and/or their designs tip obviously to one side or the other (and I do mean obviously, like comparing Peter Norvig's code to that of random undergrads).
Bias dominates every other factor, put together, times at least 10. As long as that's true, we can't say anything rational without genuinely accounting for bias. Do we actually know how to do that? The studies don't seem able to. These debates certainly don't, nor do they try. Maybe the interesting phenomenon here is actually the bias itself. Maybe it's not that we like an environment because we're more productive in it, but that we're more productive because we like it. Maybe we should get better at liking things.
The debate about this tends to remain stuck at a low level because once you've been around the block enough times you realize that it hurts to bang your head against a wall so you stop. Thus the vocal population undergoes a perpetual exodus of the experienced, but makes up for it with a fresh supply of enthusiasts, reminding one of the adage, "I arrive at the office late, but make up for it by leaving early."
TS solves problems I don’t have, and promotes a style I don’t want. I don’t want thousands of global symbols in hundreds of files in my project. At least TS has the decency to infer types in some cases, or at least put the type clutter after an identifier instead of before it, but it’s usually only superfluous clutter to me personally.
I realize that many people like TS. I just hope they understand why some of us are less enthusiastic.
Like you, I think the truth is between the extremes. My original post was just pointing out that the extreme of type-hate is not uncommon here. The opposite appears to be true as well.
Now I'm sure that many feel like that, but I don't think it's the majority, but I also don't know.
Here are some more arguments against types (don't necessarily agree with all of them myself, but for reference in the future when you want to write from the perspective of someone who feels more productive without types):
- There are other, more flexible ways to solve the same problems you solve with typing, the clojure.spec way is one of them
- You lose flexibility when suddenly everything is locked to each other by name. Even if Account and Person both has a first and last name fields, you can't use both of them if the function is expecting a Account and only use the first and last name. Then you need to add an interface, name it something, then make Account and Person be based on that. Now the function is locked to the interface, and so on
- Type checking is a very basic form of testing that doesn't solve the most common, annoying and hard-to-track down bugs, logic bugs.
- Metaprogramming becomes harder. Not impossible, just harder.
- Types (at least in TypeScript and other languages I've been using in the past) disappear in runtime, so you can't really use them. It's just a tool for you to tell the compiler what something is so it can say "no, you did wrong here"
Now I'm neither a type lover nor hater. I just want to use the right solution for the right problem, sometimes, that's making a program that will take longer time to write but specification is set in stone and requirements won't change, so types will help you a lot. Other times, it's in a very dynamic and experimental environment where you have to be able to apply changes as quickly as possible and minor errors don't matter as much, as long as you can move forward fast and test theories. Then you can go back and refactor things.
This is only true of nominally typed languages (such as... most typed languages). TypeScript is a notable exception: values just have to have the same property names and types and they'll fit. The language's philosophy is basically to describe the way people write JS rather than prescribe how people should write it, so idiomatic JS is usually easy to express in TypeScript.
TS uses structural typing.
I see this argument frequently, and it doesn't make sense to me. Take the following function below in JavaScript and Typescript:
function fullNameUntyped(obj) {
return `${obj.firstName} ${obj.lastName}`;
}
type FirstAndLastName = { firstName: string, lastName: string };
function fullNameTyped(obj: FirstAndLastName): string {
return `${obj.firstName} ${obj.lastName}`;
}
In both cases, the function's argument is bound to the interface represented by FirstAndLastName. The difference is that TypeScript allows you to be explicit about it and can statically determine if your code conforms to this. Without static type checking, you're implicitly bound to that interface.Also, you seem to have a misunderstanding. TypeScript is Duck-typed. This means that interface compliance is based on structure, not name. So the following code is correct and type-safe:
class Person {
personId: number;
firstName: string;
lastName: string;
constructor(firstName: string, lastName: string) {
this.personId = 0;
this.firstName = firstName;
this.lastName = lastName;
}
}
class Account {
accountId: number;
firstName: string;
lastName: string;
constructor(firstName: string, lastName: string) {
this.accountId = 0;
this.firstName = firstName;
this.lastName = lastName;
}
}
interface FirstAndLastName {
firstName: string;
lastName: string;
}
function fullName(obj: FirstAndLastName): string {
return `${obj.firstName} ${obj.lastName}`;
}
let person = new Person("John", "Doe");
let account = new Account("Jane", "Doe");
console.log(fullName(person)); // Prints "John Doe";
console.log(fullName(account)); // Prints "Jane Doe";
Both the Person and Account classes satisfy the interface FirstAndLastName in structure, but they don't have to reference it at all.> Type checking is a very basic form of testing that doesn't solve the most common, annoying and hard-to-track down bugs, logic bugs.
First of all, challenge. Types can help with logic bugs just fine, but also my guess would be that type bugs come up more often. This includes typos, using the wrong variables, incorrect function argument order, etc. But I'd like to see any reference for that kind of claim anyway.
Second of all, no one says you can't still can't write tests even if you're using TypeScript.
Types are some work up front but like any tool once you learn to use them it isn't really a hinderance on prototyping or experimenting-- if anything they make it easier for me. They also make it easier to refactor, since static analysis tools can help with many refactoring tasks as well.
Nah. Where did you get that? That's so horribly wrong, it's not even funny.
Types are one tool in the toolbox to describe a system. It is not the most powerful or expressive one. It just happens to be available at compile-time. It catches trivial bugs, acts as documentation, helps the compiler with memory allocation.
It also is static. And that's where the weaknesses begin. A whole class of problems that benefit from domain definitions being available at runtime are clumsy to write in languages that force types on you. Not impossible, of course, but clumsy. (i.e. place-oriented programming)
To your point:
Everyone makes mistakes. The way to catch them and to prevent them in the future is not by having types. It's by writing tests. Tests > Types > no types at all
You conveniently neglected to include (Types + Tests) at the beginning of your little food-chain there.
Went to a tech meetup group hosted at a moderate sized local tech company. The tech company had job openings, and I'd looked at a couple earlier that month. Some of their staff came to the meetup, and I got to talking with one of the 'lead' guys. I'd recently started using IntelliJ, and was talking to some others about how much more productive I was being, and it was the best money I'd spent on anything in year.
The lead guy jumped in and basically said IDEs were for wimps (more or less). If you're a good developer, you don't need an IDE - he knew everything about their codebase, was very productive, and had been for years.
My experience was the opposite - I do a lot of freelance/consulting/dev stuff - my life is jumping between projects every few months or year or so. Having tooling that helps me understand so much more about a project than I could get just from vim (for example) was so eye-opening and transformative to my way of thinking that it made me re-evaluate a lot of previous notions, habits and assumptions about development. I'd explained that using good IDEs had made me better at my craft in every conceivable way.
He just sort of shrugged and said he could understand why some people might need an IDE, but they're mostly just crutches for people who don't want to spend the time to learn a codebase the 'real' way.
I'd been interested in applying to that company, but didn't bother after realizing I would be having to work with that attitude daily.
See either Emacs or any editor using LSP such as Vim/NeoVim.
Funny, I usually see type haters claiming that they don't actually make the kinds of mistakes that are fixed by strong typing.
Which is a completely different sentiment.
As your typical type hater, my preferred argument is: yes, static typing prevents a certain class of bugs from happening; no, this class of bugs is not nearly as relevant as type lovers seem to be claiming. By an order of magnitude if not more.
Source: 6 years of being a core developer of a front end framework consisting of 1,500,000 lines of ES5 JavaScript and SASS.
I make the mistakes that are "fixed" by static typing quite regularly, but since I execute the code that I write, they don't survive.
Where static typing helps is the refactoring. You change some code; what other things have to change, where?
Although informing the process of refactoring, static typing, at the same time: (A) puts up some barriers against refactoring and (B) creates the need for a lot of the refactoring in the first place and (C) requires a more complete refactoring job than is minimally necessary to validate the idea behind the refactoring.
Refactored code doesn't escape the need for testing test. If you have some statically typed code that isn't tested well, and think you can refactor it just by making a few changes and then adjusting elsewhere to shut up the compiler, you have another thing coming.
Personally, I'm agnostic (I make mistakes in all phases and fix most of them eventually ;) )
Most of us are not optimizing for program speed. Machine time is cheap. Human time is expensive. The biggest cost-savers for most programmers will be the ergonomics of a language, not the optimizations available to the compiler.
Static types tend to push people towards copy-pasta code, as well, which can even work against performance.
You mean slower as in performance? I'm having a hard time understanding how types == performance, so you have to mean something else.
I guess assembly would be the language you would use if you really need to squeeze out the maximum amount of performance of a single CPU, and as far as I know, it does not have types.
Also languages built on top of LLVM could get by with trading compile times for run time performance. Maybe you meant compiling gets slower without types?
EDIT: my apologies to anyone who did not realize this was satirical
Otherwise it's a joy to work in, imo.
Trying to go from TS back to JS is a frustrating experience to say the least.
Doesn’t work so well with an existing codebase, but still.
The resulting JS is FAT, don't get me wrong, but since this is for internal use and it's heavily cached, I don't mind having our users download a 3MB JS file.
[0] https://www.npmjs.com/package/class-transformer [1] https://www.npmjs.com/package/class-validator
Here's what it looks like to correctly annotate an array of objects with with class-validator and json-schema annotations:
@ApiProperty({ type: Foo, isArray: true })
@ValidateNested({ each: true })
@Type(() => Foo)
@IsArray()
items: Foo[];
It's not just that you have to define everything in triplicate, it's that the failure mode for forgetting any of the above is to silently not validate your data. Unless you're very careful, you don't get the safety benefits that were the whole point of using class-validator in the first place.If I were starting from scratch, I would instead consider either io-ts or a solution that involves a code generation step, where this entire category of risk is avoided.
FWIW, I'm biased against `class-transformer` because we were wondering why some of our (TypeScript-driven) API endpoints were so slow, and `classToPlain` + `plainToClass` were the culprits, comprising 2/3 of the time spent. If you look at the source code for those functions, they're kind of insane.
As mentioned in my sibling comment to yours, I do this to define DTOs that are then expressed in JSON Schema and passed through ajv, and it's pretty slick. The objects being used are all just JavaScript objects, the class is just being used as a metadata holder and something you can reference/get via `design:type`/`design:paramtype`/`design:returntype`.
EDIT: Also, as mentioned elsewhere in this thread, io-ts is a pretty good option too!
Here I have a repo benchmarking (hopefully) all of the available runtime validation packages:
https://github.com/moltar/typescript-runtime-type-benchmarks
To implement API endpoints correctly in TypeScript, you're supposed to assume that the arguments sent by the remote client are of 'unknown' type and then you need to do some explicit schema validation followed by explicit type casting. Some TypeScript libraries can make this easier but it's misleading to say that this is a native feature of TypeScript; in fact, it is no different from doing explicit schema validation with JavaScript (there are also libraries to do this). You should always validate remote user input regardless of what programming language you use.
Merely getting the compile-time static type checker to shut up because the types in your client code match the types in your server code is not good enough unfortunately - In fact, it may conceal real issues by giving developers false confidence that runtime type validation is happening when in fact it is not. A hacker could write a client in a different language and intentionally send incorrect input to crash your server unless your server explicitly validates the schema.
The reality is that there is no guaranteed type continuity/consistency between the client and the server. Any tool which gives the illusion that there is any kind of continuity is deceptive by design.
This is why I like plain JavaScript; it requires real discipline and it doesn't give any sense of false confidence. Developers should always be on their toes. The only way to improve code quality and security is by exercising more caution, not using more tooling.
The benefit pointed out by the author of this article is in fact one of the few genuine gaps in TypeScript's type safety capabilities. Praising TypeScript for this fictitious feature is only going to give developers false confidence that TS somehow takes care of input validation for them and this is going to lead them to getting hacked.
Our system uses io-ts to dynamically validate all incoming and outgoing API data. The static API types are guaranteed to match the io-ts codecs, so the runtime validation will match the static types.
Re: "it's misleading to say that this is a feature of TypeScript": I didn't say that. TypeScript makes this kind of static verification possible. It's impossible in JavaScript.
Re: "The benefit pointed out by the author of this article is in fact one of the few genuine gaps in TypeScript's capabilities": yes, it's a gap in TS. Again, TS makes it possible (as opposed to JS). io-ts (mentioned explicitly by name in the article) backfills the type erasure shortcoming for our purposes, at the expense of being more verbose and producing worse error messages when compared to first-class reflection in a non-type-erasing language.
Re: "going to lead to them getting hacked": no, io-ts isn't going to lead to that more than any other runtime validation scheme. If someone believes that TS' static types provide runtime guarantees, yes, they could write highly insecure API code. But it's hard for me to imagine someone getting to an experience level where they can write a server-side router that's generic over all possible API endpoint payloads, while at the same time not knowing that TS erases types at runtime. Erasure comes up early in the process of learning TS because it leads to surprising behavior, like objects at runtime having properties that aren't present in their static type.
It's definitely possible (just as easy in fact). You just need to define a schema for each API endpoint. TypeScript does not physically protect you from having to enumerate all the properties and size constraints of the data one by one. In terms of the actual schema validation step, there are lots of tools in JavaScript which let you do the same thing; ajv, z-schema are just a couple of examples.
My point is that TS adds no value there. TS's value is only in static type checking. What the article is claiming is that TS somehow adds value with runtime type checking.
The argument of saying that "TypeScript adds value because it can reuse its internal type definitions for the purpose of validating remote input" is circular - It refers to a problem which doesn't exist in JavaScript to begin with.
JavaScript has no type definitions so being unable to reuse type definitions for schema validation does not qualify as a drawback on its part. The argument simply does not apply and cannot be used to claim TS's superiority.
At best you could claim that TypeScript cancels out one of its own shortcomings:
- TS shortcoming: You need to define types everywhere... That adds a lot of work! (-1 point)
- TS benefit: But you can re-use these type definitions for doing schema validation of user input as well! That saves a lot of work! (+1 point)
But the net gain over JS is 0 because:
- JS shortcoming: You need to define a schema for all your endpoints to validate user input... That adds a lot of work! (-1 point)
- JS benefit: But aside from that, you don't need to define types anywhere... So that saves you a lot of work. (+1 point)
The only real argument to be had is whether or not compile-time static typing adds value over dynamic typing.
https://github.com/EXXETA/openapi-cop
This is cool for dev mode but you do not always want it in production because deep validation of all requests and responses takes many cpu cycles.