8

Type safety on the web with TypeScript

 2 years ago
source link: https://devm.io/typescript/type-safety-typescript
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Do we still develop with JavaScript on the web at all, or do we only use TypeScript? Is TypeScript the end of the line or is there still more to come? The topic of typing on the web is perfectly arguable, so let's take a look at the situation.

TypeScript, JavaScript, or maybe something else entirely?

We JavaScript developers already have a hard time. We’re ridiculed by the whole world because of our favorite language’s shortcomings. But let's face it: JavaScript is where Java’s always wanted to be: on every device. Whether it's a smartphone, a full-blown desktop computer, a car, or a household appliance, we encounter JavaScript everywhere these days, and not because it's the best language in the world—no, it most certainly is not. The language was in the right place at the right time, was widespread enough, and there are enough people who know it—more or less. As so often in history, the same is true here: The best solution does not necessarily always prevail.

But now we’ve got the language and we have to make the best of it. So let's take a look at its biggest annoyance: the completely chaotic handling of data types or their absence. But many people forget that JavaScript has a type system, the language is just not very picky about types. To put it diplomatically: JavaScript is weakly typed.

Fine, but what does this mean for us and our daily work? The first problem is that we can define a variable and do anything we want with it. For example, I can initialize a variable with the value 42, then assign it the value true. Since that's not enough, the variable also gets an object or array as a value afterward.

Why is this flexibility bad? Quite simply: it severely limits the source code’s predictability. Variables are just one example of JavaScript’s lax handling of types. It continues with functions—more specifically—with the signature of functions. If you’ve ever integrated a JavaScript library, you probably know the problem: What should I actually call the function that the library provides me with, and what do I get back? In a strictly typed language, the signature of functions is also typed, meaning I know exactly what goes in and what comes out. Not so in JavaScript: I can call a function with too many, too few, or just the right number of arguments. We don't even need to talk about types. A JavaScript function also always returns something, even if it's just undefined. But what exactly comes back is left to the author’s creativity.

Then again, as a developer...


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK