DEV Community

Ben Halpern
Ben Halpern

Posted on

Convince me that types are awesome

Suppose I've mostly used untyped programming languages and don't have a great appreciation for types.

Let's do some convincing!

Oldest comments (60)

Collapse
 
dimgrav profile image
Dimitris Gravanis

Less coding errors, code readability, easier debugging, aka quality of life!

Collapse
 
lampewebdev profile image
Michael "lampe" Lazarski

I'm on @ben side here I don't fully see the point of types.

I don't have seen any bigger proof of these claims.

So can you maybe elaborate a little bit on your claims?

Thank you <3

Collapse
 
dimgrav profile image
Dimitris Gravanis

A statically typed environment makes you less error prone. It enforces certain basic requirements and this is a mindset that you carry with you when moving to a dynamically typed language, which I personally found very helpful when I started getting more into JavaScript, coming from a Java and (PEP8) Python background.

I think it has made me more aware of the data flow in my code and better at designing the architecture of any system.

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

Is @ben saying that he doesn’t like types?

I thought he was just doing a spectacular job of sparking good conversations.

That being said, using a type system isn’t always about the technical aspect. Often times there are emotional benefits:
dev.to/cubiclebuddha/communicating...

Collapse
 
deciduously profile image
Ben Lovy • Edited

With types, you can make illegal states unrepresentable. Instead of storing a bunch of strings, you can store a Name and and Address, and can encode into the type system that ContactInfo must contain a phone number, an email address, or both but not nothing. By encoding that requirement into the type system, it becomes impossible to represent an incomplete record in your program. It also aids refactoring - if your business logic changes, your compiler will guide you through the refactor for ensuring your whole codebase reflects the change.

Collapse
 
johnpaulada profile image
John Paul Ada

I agree with this. I recently tried out ReasonML and it's awesome! Nevermind less rope to hang yourself with, it really gives you no rope! I'm still trying to learn more about it though, like about phantom types and some clever ways to use types to enforce structure and rules in your code without using a single conditional statement.

Collapse
 
cubiclebuddha profile image
Cubicle Buddha • Edited

There are so many articles on the technical reasons why you should use TypeScript, but very few explain why using TypeScript might make your team happier. I think it’s important to note that TypeScript’s type system is MUCH more forgiving and expressive than other type systems I’ve used like C# and Java. Jump on the TypeScript train and enjoy the happy times! :)
dev.to/cubiclebuddha/communicating...

Collapse
 
briwa profile image
briwa • Edited

One of the best advantages of types is that it lets you catch errors before the code is executed. With the right precompiler/language server, you can see that your code is faulty even in your IDE. I can only speak for Javascript to give you an example.

function sum (num1, num2) {
  return num1 + num2
}

const total = sum.apply(null, [1,2])
// Returns 3.

It is a sum function that takes in two numbers as the arguments. However, a common mistake is to think that the sum function can take in multiple arguments then get a sum of them. Maybe the function is imported into a different file and you might have already forgotten about the interface.

const anotherTotal = sum.apply(null, [1,2,3])
// You're expecting it to return 6, but... it's actually still 3.

Unfortunately, you wouldn't know that you're making a mistake until you run the code in the browser and test the feature that is using the code, or you have your unit tests running. The scariest part is, in the browser, it won't even throw an error.

With Typescript, you can spot this in your IDE even before it is run anywhere else. This is how it looks like, more or less:

const anotherTotal = sum.apply(null, [1, 2, 3])
//                                ❌ ^^^^^^^^^
//  Argument of type '[number, number, number]' is not assignable to parameter of type '[number, number]'.
//    Types of property 'length' are incompatible.
//      Type '3' is not assignable to type '2'. ts(2345)

This is just a really simple example. Of course, the mistake is obvious on this one, but, as the software gets more complicated, the argument for the necessity of typing (IMO) is going to get more and more valid. For more info on this topic (Typescript), I've written an article about this (shameless plug πŸ˜‹):

Another advantage that I find it useful is the documentation. With a good IDE integration, Typescript (or any strongly-typed language) code is sort of self-documented, but if you want to take it up a notch, you can easily generate a user-facing documentation from it without a hassle, using libraries like Typedoc. It would help a lot for, say, you're creating a library in Typescript and you want to put up a page for the API documentation.

But I also understand the other side of the story. I've read this article, and I can see that the overhead of using Typescript (or any strong-typed language, for that matter) can be too expensive to some. I would say, if you still want to skip typings, at least have a good documentation and a good testing coverage. Without these two (and also typings), I'm not sure if maintaining the code would still be productive when the code is growing in complexity and also the number of devs maintaining it ;) Just my two cents.

Collapse
 
mandaputtra profile image
Manda Putra

How about user input? you define as a number but user inputted string? you catch the error or the compiler throw the error?

Collapse
 
stojakovic99 profile image
Nikola StojakoviΔ‡ • Edited

User input is done during the runtime, so, you need additional measures to catch the error. Personally, for TypeScript I use class-validator and treat whole API request as DTO. For Java I use bean validation.

Thread Thread
 
mandaputtra profile image
Manda Putra • Edited

Yes, that's it, I use typescript before I do what you do too, this is why I'm still not using it (Unless I use Angular). if I want to sell TS to somebody else definitely not the typing system. the IDE and OOP make the refactoring code better, autocomplete, what else, typing system doesn't make less bug and maintaining code better.

Just use this, basarat.gitbooks.io/typescript/doc... reading this makes me use typescript for 2 months. then back again to plain javascript, some problem with another lib still sometimes occurs in TS (usually typings). I can't stand that :(

Collapse
 
briwa profile image
briwa • Edited

If you're talking about Typescript, it won't catch them, because in my opinion Typescript is not meant to be used to define user interfaces and user inputs (unless you're talking about .tsx files, but it's going to get too specific, which is out of topic). In general, side effects I/O such as user inputs should be validated/specified by an end-to-end test.

In HTML, you can definitely set a "type" to your inputs (for example <input type="number" /> for number-only inputs). But again, the context matters. If you have a use case and you have your own set of expectations of what a strongly-typed language should do, maybe I can understand your problem better.

EDIT: @stojakovic99 answer is more apt, I guess it's better for me to say that strongly-typed languages help you to define/catch errors before runtime, and outside of that (like user inputs) it should be handled differently (maybe an e2e test).

Collapse
 
jckuhl profile image
Jonathan Kuhl

User input cannot be caught by Typescript, because user input is brought in at runtime.

You don't run Typescript, you compile it to JavaScript and run the JavaScript, so by the time it's running, type information is discarded.

However, Typescript will help you prepare a function to receive user input by setting up the appropriate types, but that's as far as it can go.

Collapse
 
isaacdlyman profile image
Isaac Lyman • Edited

For me the main benefit of types is not correctness but developer tooling. If you're in a language/project with types, using and extending existing code is a snap because the IDE will auto-complete stuff. You'll know exactly what each class and method does and what parameters it expects. Even if you're using a third-party library with poor documentation, you can sniff out the available functionality using your IDE's code hinting feature.

As for correctness, I have yet to see evidence that typed languages are less error-prone than typed languages. Admittedly I avoid a null reference error a couple times a day when using TypeScript or C#, but I tend to think I would have found those anyway, albeit not as quickly. And if not, perhaps they didn't matter.

Collapse
 
auroratide profile image
Timothy Foster

To the person:

You already use types (: You don't use your chair to start your car. You don't pour water on your computer so you have something to drink. But you do use a cup for water, or perhaps a mug, or even a milk carton if you wanted. We group real-life objects like this to keep ourselves at least a little more organized in such a chaotic world.

Types are kinda like this in the programming world ^

(admittedly it's not a perfect analogy, especially because I'm a huge advocate for functional freedom, but it's a start for at least gaining an intuition)

Collapse
 
anwar_nairi profile image
Anwar • Edited

Good one!

Had a bad experience with using Typescript on my latest npm package (because ServiceWorkerGlobal was very hard to use in another context than a service worker, very tough to work out in a class) and I moved to plain, untype-hinted Javascript and so far I am happy with it.

For the debate on the pros/cons, I will let my peers to answer because I have not enough experience on typed programming!

Collapse
 
hamishdickson profile image
Hamish Dickson • Edited

Imagine you have this function

def combine(a, b) = ???

how would you test this does what you think it should do? The way this is written combine can accept any a or b and can return anything

Now lets add some types

def combine(a: Int, b: Int): Int = ???

For your program to compile a and b must both be of type Int and combine must return an Int. This means rather than testing every possible input and output, you now only consider a tiny subset of the inputs/outputs you originally started with

Here's another example. This function is parametricly polymorphic in T (that's what the square brackets are saying), we must take a T and must return a T

def thing[T](a: T): T = ???

Can you think of an implementation other than this? Remember T can be anything, so the implementation must work for any possible T

def thing[T](a: T): T = a

I can't. And in fact the types have limited the space of implementations for this function down to just this and things like just throwing an exception or doing a side-effect.

Depending on your language you can go really far with this. In lots of FP languages OOP is never used and instead ad-hoc polymorphism (aka typeclasses) is preferred. The idea is really just an extension of the idea "my program won't even compile if the types don't work". If your language has higher kinds, you can meaningfully talk about things like IO and sequential/parallel computations. If you have a language like Idris with dependent types, you can do type-driven-development, where each time you compile your program you do a "proof of correctness" (note the quotes before you start yelling at me :) )

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

Slow down there! You already got a response from me today about switch. :D

I can talk for days, literally days, about how awesome types are and the problems with untyped languages...

...though I figure I might not have to, in about a year, as the dev codebase grows, and the contributors increase, you'll look back at this post and cringe. ;P

Collapse
 
nickytonline profile image
Nick Taylor • Edited

I'll keep it short. There are lots of merits to types, but I think the big ones are discoverability and avoiding mistakes at compile time. Couple this with an editor and you can end up with great refactoring tools. And no, types are not a silver bullet. πŸ˜‰

Thanks for coming to my Ted talk.

Collapse
 
rinaldorex profile image
Rinaldo Rex

Simple, yet very rational!

Collapse
 
nqthqn profile image
nqthqn

I didn't realize this was a debate. What is 1100101110001? You have to know the type to figure it out. Is it an integer? A letter? A string? A pointer? Types are essential for doing stuff with computers.

Should you use a typed language? It depends. Are you writing short scripts? Then the overhead can be annoying. Are you writing a large application? Then the types can help ensure system integrity.

Mic drop.

Collapse
 
itsjzt profile image
Saurabh Sharma

Its a different experience I usually had experience with dynamic typed language (js, python) and later I used typescript at work. It was really great experince. First I was fighting with the type system later I started liking it more and more

P.S just give it enough time.

Collapse
 
minkovsky profile image
Filip

Personally I'd prefer a compiler error in one minute versus debugging a TypeError (or worse, non-exception buggy behaviour) caused by something being undefined at runtime where it takes me 5 minutes and a series of steps to reproduce. Types really do reduce the frustration factor in JavaScript.

Collapse
 
eli profile image
Eli Bierman

Your code can prove things about your code and that's pretty awesome.