It seems like people are trying to use types as a substitute for tests and a way to protect themselves from unintended mutations.
But if you write tests already and use immutable data structures, what benefits does TS bring to people whose background isn't in strongly typed languages?
- Documentation. You don't need to have free-text comments saying "@param myArg must be a string", you can just look at the type signature, and immediately know how to use a function. Attempting to pass in a number will fail at the time of writing, not at runtime (of your test). This is a huge benefit when using third party libraries. For a JS lib, you need to read the documentation, and if something is undocumented you need access to the source code and the time to analyse it, to understand exactly how to use the lib. Compare this to making the type interface available.
- It's easier for a machine to read, which means the possibility for better tooling. e.g. linters and checkers, automatic refactoring.
- It's actually faster to write, due to the ease of making changes. If you move a function out to a new module, the compiler will immediately tell you all of the invocation sites that are now broken. (If you rely on tests, you have to make sure you have tests in every invoking module, rather than just the module you are actually changing. [Ignoring mocking issues...])
I'm not so sure about the "faster to write" since my IDE and linting will already take care of that. The java-style boilerplate is a huge turnoff for me, and the validation seems to produce false negatives so often as to actually introduce more bugs. Ie, If a variable gets mutated without changing type, TS is now worse than useless for validation.
The self-documenting part is the strongest argument I've heard, but writing real documentation and real tests still seems better.
An IDE can assist you even better when it can understand the code you're writing. For example, autocomplete "myString.re" without type hints, and an IDE like IntelliJ might suggest the method "reject()" (which is found on a Promise interface), or "remove()" (which is found on a DB entity interface), as well as "replace()" (which is found on a String interface). Wouldn't it be nice for it to always pick the right option?
TypeScript doesn't help with immutability at all. For that, you should look at something like PureScript. (Or GHCJS, or any other compile-to-JS languages that support immutability.) TypeScript assumes you are sticking with JavaScript's semantics, mutability and all. If you want immutability, you still need to use "Object.freeze()". Variable mutation is not something picked up by types alone.
There are other languages that introduce "dependent types", which can actually include values in their type signatures, which might be able to specify something like you want; i.e. "a function that accepts an argument of type 'a' which derives a number, and returns the same type 'a', but the returned value must be equal to the input value plus 10".
Documentation is nice... or so I've heard! Speaking for myself, developers are lazy and just want to write code. Why not make them document the code as they write it? Plus, external documentation (even as JavaDoc-style comments) always falls out of date with the code.
I think better than tests, is to enforce "design by contract" - assert your preconditions and postconditions on every function. This inlines your assumptions and behaviour verification with the actual code to be run. (If performance is a concern, you can implement this in a way that allows you to disable assertions.)
In general, the more guarantees you can enforce at compile time (such as only accepting certain types of values, or that input values are never mutated in place), the less need there is for having twice as much testing code as application code.
Refactoring. Say you want to make a 1:1 relation into a 1:* relation. You change your core data type from e.g. `type person{address:string}` to `type person{addresses:string[]}`, follow/fix all the red squiggly lines until it compiles, and generally you're done.
OTOH with unit tests, you've got to find/fix not only your app code but the test code as well. You may forget some things because you overlook a function and its tests. And of course your test coverage is likely not 100% so things may slip through.
So in addition to "refactoring", I'd add "guarantees": literally one line of code gives you 100% coverage.
PLUS autocomplete. JS editors have gotten better, but TS blows them out of the water. Importa new library, and stuff almost codes itself.
Mutability is somewhat orthogonal to the discussion. You can write things immutably or immutably in typed or untyped languages. I prefer mostly immutable too. But, going with it, I'd been a Clojure fan for a couple years, where immutability and dynamic types are both forefront. After rewriting an app in F#, and then performing a major refactor, this is what I had to say about it. https://disqus.com/home/discussion/owenrh/the_beauty_of_cloj... tldr: refactoring is much easier with types backing you up.
n.b. There's no reason you have to choose. You can have all three. Immutability, tests, and types. I do. Though if I had to choose, I'd pick types first. I'm a disciplined enough coder that immutability guarantees aren't that necessary, and if I've got types and discipline, then tests usually are unnecessary.
But doesn't Typescript compile to JS, thus there's actually no type-checking at runtime?
Certainly type checking can prove that it's the right type, but in my experience knowing that it's the right type but the wrong data is useless, I care if it's the exact data it's supposed to be.
How does type checking protect you (or someone else) from inadvertently mutating a value without changing it type and causing problems later? It's perfectly possible to do this without having any checks for class/instance throw a warning, unless there's something I'm missing.
> But doesn't Typescript compile to JS, thus there's actually no type-checking at runtime?
Sure, but that's what happens in every other language e.g. C's type system will enforce certain properties for you but when you compile to machine code the machine code is not checking those properties at runtime. If you know the compiler is correct you don't have to worry.
Nobody is saying you should stop writing tests but a good type system will mean you have to write less tests because the type system will do some of the checking for you in a more robust way.
You claimed that the lack of type checking at runtime is somehow detrimental to the notion. He pointed out that, fundamentally, all strongly typed languages run as weakly typed machine code at runtime, giving C as one obvious example. Thus, types in TS are at least as useful as types in C.
The concrete advantage of TS is the same as the concrete advantage of any strongly typed language - types let you do static validation, and unlike tests, they allow for that validation to be provably complete (of course, the domain of constraints that can be so validated depends on the power of the type system in question).
Yes, but what about mutating objects/primitives in a way that causes all validations to pass but still be passing the wrong data?
It seems like using type checking as a reason to write fewer tests actually just creates nastier bugs in areas where your coverage is based on type validation.
What am I missing about checking type mutation !== mutation being a problem?
What is the advantage of strong types if your data structures are immutable? Is there any? I'm genuinely trying to understand if TS is just for cases where uncontrolled mutation is the norm and test coverage is poor.
Immutability is also something you can model in the type system (not currently in Typescript, but it is possible in other languages).
That said, immutability by itself won't save you from passing the wrong shape of immutable object into a function, just as validating the shape of the argument passed and the argument expected against each other won't help if there are other assumptions being made by the code (such as that the object cannot be mutated). As one of the parent comments pointed out, types are proofs. Not everything can be proved to a compiler, but (assuming a bug-free compiler) everything which can be proved to a compiler does not need any additional tests. Things which cannot be proved to a compiler will need tests, of course.
> Yes, but what about mutating objects/primitives in a way that causes all validations to pass but still be passing the wrong data?
> What is the advantage of strong types if your data structures are immutable? Is there any? I'm genuinely trying to understand if TS is just for cases where uncontrolled mutation is the norm and test coverage is poor.
Can you give an example? I'm not following what you mean. Why would strong types be less useful if your data structures are immutable? OCaml mostly uses immutable data structures for example but its strong type system is fundamental to why it can be used to write such robust code.
Typescript has a stronger type system than JavaScript so Typescript can therefore capture more program properties statically compared to JavaScript whether you're using mutable data structures or not.
> knowing that it's the right type but the wrong data is useless, I care if it's the exact data it's supposed to be
Entirely possible people are comparing apples to oranges here. My experience is all based on structured data; e.g. User, Address, Order, Product, etc, and the relations between them. Data is generally static throughout the duration of the call; e.g. CRUD app.
It sounds like your experience is more with raw numbers and collections, and higher rates of entropy. In that case, I can see how types wouldn't add much value, and tests would be far more essential.
The whole point of strongly statically typed languages is that the proofs are performed at compile time. Statically typed programs shouldn't change behaviour after type erasure.
Languages with strong enough type systems can statically guarantee that data is structured correctly at runtime. Stronger structural requirements require stronger type systems. Algebraic data types are sufficient for many common static structuring guarantees.
You are correct, there is no type-checking at runtime. Getting garbage data where you are expecting properly formed data will throw a nasty wrench in your application.
It's not just javascript with types. The language is written in a way that makes it much easier for machines to understand your code. I'm not talking about just tests and linting.
Check out some typescript tooling videos, this one was shown at an angular 2 conference but you don't need to know any angular to watch it:
I find it funny that a lot of reasons boil down to "it's easier for the machine" -- developer happiness (which most of you mentioned, too!) through autocompletion and less failures seem to be a better selling point :)
A major benefit is the ability to quickly understand code you didn't write because you have the ability to 'go to definition' or 'find all references' which works across multiple files. On top of that once you understand the code and need to modify it you can quickly refactor across multiple files instantly and with a high degree of confidence.
Types are not a substitute for tests, but they eliminate an entire class of bugs that are screened out at compile time. That way you can focus your tests on functionality and not silly mistakes.
Which ide are you using? WebStorm, for example, gets easily confused about common JS idioms, which makes its tipped hinting useless in many situations. This makes refactoring a pain since you can't perfectly trust its warnings.
But if you write tests already and use immutable data structures, what benefits does TS bring to people whose background isn't in strongly typed languages?