JavaScript を捨てて TypeScript を学ぶ必要があるのはなぜでしょうか? TypeScript と JavaScript

Barbara Streisand
リリース: 2024-11-15 00:53:02
オリジナル
433 人が閲覧しました

Vous n'êtes pas marié à JavaScript, peu importe à quel point vous l'aimez, vous devez essayer TypeScript. Peut-être que vous n'avez aucune raison de déménager, mais je vais vous emmener dans un voyage, où vous aimeriez goûter un peu à TypeScript. Je peux vous donner plus de 13 raisons pour lesquelles vous devriez passer à TypeScript, mais pour l'instant, je vais essayer de vous convaincre de passer à TypeScript en 5 points où je vous expliquerai pourquoi TypeScript est bien meilleur que JavaScript pour le développement, et pourquoi vous devriez choisir TypeScript pour votre prochain projet.

JavaScript strictement typé

Why you should learn TypeScript and ditch JavaScript? TypeScript vs JavaScript

TypeScript n'est rien d'autre qu'un javascript strictement typé. L'une des raisons pour lesquelles je déteste JavaScript (oui, je le déteste) est qu'il y a tellement de flexibilité dans le langage qu'il n'y a pas de règles ni de réglementations, vous pouvez écrire n'importe quoi et cela ne vous donnera pas d'erreur (il y a des exceptions) , par exemple, si vous avez créé une variable et lui avez donné un numéro comme valeur, disons 6, plus tard vous pourrez attribuer une fonction à la même variable, et même appeler cette variable, cela me semble un peu drôle, de toute façon, voyons quoi TypeScript a à voir avec ça.

En dactylographié, lors de la définition d'une variable, vous devez écrire son type, comme si la variable stockerait un nombre, un tableau, une chaîne ou toute autre chose. Une fois que vous l'avez fait, vous ne pouvez plus y stocker quoi que ce soit d'autre, sinon TypeScript ne vous laissera pas continuer, et TypeScript est strict à ce sujet.

let age: number;
age = 25;

ログイン後にコピー

Même si vous ne mentionnez pas le type de la variable et ne lui attribuez pas une valeur, il est trop intelligent qu'il découvre automatiquement le type à partir de la valeur donnée et s'en souvienne.

let age = 10;

age = "Donald Trump"
~~~
// Type '"Donald Trump"' is not assignable to type 'number'.(2322)
ログイン後にコピー

Si vous connaissez les langages comme C/C , là, le type est défini comme int age ; de même, dans TypeScript, nous définissons le type après le nom de la variable après un signe deux-points, comme ceci let age: number;. De cette façon, nous avons simplement bourré TypeScript sans modifier la syntaxe JavaScript. C'est ce que je vous ai dit au début, TypeScript n'est pas seulement du JavaScript, avec juste des types. Je ne me concentrerai pas sur la syntaxe du TypeScript, cela n'entre pas dans le cadre de cet article.

Maintenant, si c'était JS, vous pourriez faire n'importe quoi avec l'âge, en lui attribuant votre nom, ou un tableau, ou même une fonction, mais dans TS, une fois qu'il est né sous forme de nombre, il restera un nombre , rien d'autre. Si vous le faites, cela vous donnera immédiatement une erreur, mais en JS, il la tolérera tant que vous ne faites pas quelque chose d'illégal, comme appeler age sans lui attribuer de fonction ou accéder à la propriété .length quand c'est le cas. une fonction.

Au début, cela peut vous sembler inutile de passer de JS à TS, mais une fois que vous l'avez bien compris, vous n'avez jamais voulu coder en JS à cause de cette fonctionnalité uniquement.

Because you need errors.

Why you should learn TypeScript and ditch JavaScript? TypeScript vs JavaScript

When I say you need errors, doesn't mean I want you to write errorful codes, but the code you've written must be error-free, and for that, it is the job of your dev environment to give you errors. And in JS, it just doesn't do it, it is one of the reasons people love it, and at the same time hate it too. When I say errors, I mean everything except syntax errors. JS doesn't give an error when you write something wrong, but it gives you an error when something wrong happens. So if some part of your code isn't executed at the time of testing, then be ready for some pain in the production. :)
Let's see an example

I'm writing a code to multiply two numbers, I'll do this in both JS and TS, and you'll see how JS is so unreliable and may break your application in many ways.

function multiply (num1, num2 ) {
    return num1 * num2;
}

console.log(multiply(3, 4));
// returns 12

console.log(multiply(3));
// return NaN

console.log(multiply(3, null));
// returns 0

console.log(multiply());
// returns NaN
ログイン後にコピー

You can literally call multiply in any manner, there's no restriction, and it always gives you unexpected results, that's the worst thing about JS, suppose now you have to use those returned values somewhere, how much inconsistency and unexpected results it causes in your application.

But thanks to TypeScript, it is very strict, it won't let you proceed if you do not follow the rules if the function expects the, then you must pass the number, and it says both should be numbers, then you have to pass two arguments and both must be numbers. Let's see the same code in TypeScript. If you're not aware of the TS syntax, don't worry, it is similar to JS, except the return type comes before the opening brace and argument types with their names.

function multiply (num1:number, num2:number) :number{
    return num1 * num2;
}

console.log(multiply(3, 4));
// returns 12

console.log(multiply(3));
//          ~~~~~~~~~~~
// Expected 2 arguments, but got 1.(2554)
// input.tsx(1, 33): An argument for 'num2' was not provided.

console.log(multiply(3, null));
//                      ~~~~
// Argument of type 'null' is not assignable to parameter of type 'number'.


console.log(multiply());
//          ~~~~~~~~~~~
// Expected 2 arguments, but got 0.(2554)
// input.tsx(1, 20): An argument for 'num1' was not provided.
ログイン後にコピー

So here in TS, there are never unpredictable results, you can only proceed when you remove all the errors, that's what makes me fall in love with TS <3

TS is not just bound to tell the errors in your code that you've written, but it also tells you the possibility, of where an error may come. Let's see a quick example of this.

// I'm writing some TS code, you can ignore it and look at the comment, I've written in the code.

// Type is user
interface User {

    // Property is name of type string
    name: string;

    // Property is age of type number
    age: number;

    // Property is social which is optional and have properties
    social?: {

        // Property is facebook which and have type string which is optional
        facebook?: string;

        // Property is twitter which and have type string which is optional
        twitter?: string;
    }
}
ログイン後にコピー

Now as you can see, the social property is optional means there may be cases where social is undefined, TS knows that, and it will not let you proceed until you handle it.

let userData:User = dataFromSomeSource;

console.log(user.social.facebook);
//          ~~~~~~~~~~~
// Object is possibly 'undefined'.(2532)

if(user.social){
    console.log(user.social.facebook);
}
ログイン後にコピー

So, this is silently ignored by JS, and it causes errors from case to case, which is another reason why TS is considered more reliable.

Auto Tested and Documented.

Why you should learn TypeScript and ditch JavaScript? TypeScript vs JavaScript

Suppose you're using a function from some library written in JS, how would you know what params you've to pass? You will go to the documentation, you'll check what params it will take, which of them are optional, and then you'll call the function. But in TS, there's no need to document that, everything is explained by the types themselves. Even it also ensures that you're using the function in the right way, and not passing any random parameters.

For example, you can refer to the second section above.

Another case you can take is, suppose you're using a library that gives you a JS object, with nested properties, so to check what exactly the names of the properties, and which of them can be undefined, is a big pain. You have to dig in the documentation, or sometimes console log your object to see what stuff it contains. That's really what I hate, I wish some way, where the object itself tells you what properties it contains and if some property is undefined, or property has a value string or number or array or what. Well, the wish is fulfilled, thanks once again to TypeScript. If the codes are written in TS, the exact behaviour you'll get. Let's see with an example.

function getUser ( id: number ):User {
    // Some logic to get the user from id.
    let user:User = {name: "Bob", age: 24};

    return user
}

let user: User = getUser(1);
ログイン後にコピー

Now to check what properties the user will have, no need to console log it, or go to the function definition when you add an . after user, it automatically gives you the list of properties it has, and also tells you which of them are undefined. See the image below.

Why you should learn TypeScript and ditch JavaScript? TypeScript vs JavaScript

It also automatically tests your codes by checking all the possibilities and tells you if any of the possibility fails. Sounds amazing right, well yes, it is. This feature prevents a huge number of bugs at the time of development, you don't need to write a test for your function nor need to test it manually at different values, TS do it for you and tells you if you've missed something that may cause a problem later.

In the code below, I have written a function that takes two arguments and returns an array of string by adding each parameter to the array if they are not undefined. The first argument is required while the second is optional.

function arrayFy (name1:string, name2?: string): Array<string> {
//                                                ~~~~~~~~~~~~~
// Function lacks ending return statement and return type does not include 'undefined'.(2366)

    let resultArray = [name1];

    if(name2) return resultArray.push(name2);
//            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Type 'number' is not assignable to type 'string[]'.(2322

}





</p>
<p>The code above is a very common scenario for me to make a mistake. Array.push does not return the updated array, but returns the new length of the array. So if the above code is written in the JS, there won't be any error, and my code just runs and gives expected results, which I have to debug and find the mistake here, and my function is returning 2 if I pass the second argument too. But here in TS, you can clearly see that TypeScript automatically run the case, and tell you that in that particular case, your function will fail to return an array of strings. </p>

<p>There's another error, say if you don't pass the second parameter, you're still returning nothing (undefined), which also violates the behaviour of your function as it must return an array of strings. So, here I made some changes in the function and TS gives you a green flag, which means the function will never ever give you an unexpected result. See below.<br>
</p>

<pre class="brush:php;toolbar:false">function arrayFy (name1:string, name2?: string): Array<string> {

    let resultArray = [name1];

    if(name2) {
        resultArray.push(name2);
    }

    return resultArray;

}

ログイン後にコピー

Always a few steps ahead of JavaScript

Why you should learn TypeScript and ditch JavaScript? TypeScript vs JavaScript

Typescript is always a few steps ahead of Javascript. If a new feature is announced in JavaScript, and it is supposed to be released in the next ECMA release, TS release it before the official release and you can use it without any worries of compatibility in browsers as you can compile TS to any previous version of JavaScript (like ES5). TypeScript has a lot of features that JavaScript doesn't.

So we can say that TypeScript is also a superset of JavaScript, ECMA5, ECMA6, ECMA7 and ECMAnext, and some features that don't even exist in JavaScript.

Conclusion

Why you should learn TypeScript and ditch JavaScript? TypeScript vs JavaScript

Yes, sooner or later, you have to accept TypeScript. You just can't run away from it. Every npm package either being written in JavaScript has to provide its types too, or another package with typescript support is preferred. Now, most of the large libraries, packages, and frameworks are being written in TypeScript.

In the beginning, packages used to be in JavaScript with TypeScript support too, but now the table has turned, and packages are in TypeScript and they are giving support to JavaScript. Everyone is acknowledging the power and need for TypeScript over JavaScript and accepting it.

You'll never be able to learn Angular, as it forces you to write only TS code, the same case with the loopback 4. NestJS primary language is TypeScritpt and they also provide support for JavaScript. Following are the words of NestJs

We're in love with TypeScript, but above all - we love Node.js. That's why Nest is compatible with both TypeScript and pure JavaScript. Nest takes advantage of the latest language features, so to use it with vanilla JavaScript we need a Babel compiler.

If you're still not satisfied with the reasons I gave you, and have some counter questions, you can anytime contact us, and believe me, it is worth giving a try, you won't regret it.

以上がJavaScript を捨てて TypeScript を学ぶ必要があるのはなぜでしょうか? TypeScript と JavaScriptの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート