Heim > Web-Frontend > js-Tutorial > Hauptteil

Warum sollten Sie TypeScript lernen und JavaScript aufgeben? TypeScript vs. JavaScript

Barbara Streisand
Freigeben: 2024-11-15 00:53:02
Original
433 Leute haben es durchsucht

あなたは JavaScript に慣れていませんが、JavaScript がどれほど好きでも、TypeScript を試してみる必要があります。もしかしたらあなたには引っ越しする理由がないかもしれませんが、TypeScript を少し味わってみたい旅に連れて行きましょう。 TypeScript に移行すべき理由は 13 以上挙げることができますが、今のところは、開発において TypeScript が JavaScript よりもはるかに優れている理由を 5 つのポイントで説明し、TypeScript に移行するよう説得してみます。次のプロジェクトに TypeScript を選択する理由。

厳密に型指定された JavaScript

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

TypeScript は、厳密に型指定された単なる JavaScript にすぎません。私が JavaScript が嫌いな理由の 1 つは (はい、嫌いです)、この言語には非常に柔軟性があり、ルールや規制がなく、どんな駄文を書いてもかまいませんし、エラーも発生しないことです (例外はあります)。たとえば、変数を作成し、それに値として数値 (たとえば 6) を与えた場合、後で同じ変数に何らかの関数を割り当てることができ、さらにその変数を呼び出すこともできます。これは私には少し面白いように思えます。とにかく、何が起こるかを見てみましょう。 TypeScript と関係があるそれ。

typescript では、変数を定義するときに、変数が数値、配列、文​​字列、またはその他のものを格納するのと同じように、その型を記述する必要があります。一度これを実行すると、そこに他のものを保存することはできなくなり、TypeScript では続行できなくなります。TypeScript はこれに関して厳密です。

let age: number;
age = 25;

Nach dem Login kopieren

変数に型を指定せずに値を代入しても、与えられた値から自動的に型を見つけて記憶してくれるのは賢すぎます。

let age = 10;

age = "Donald Trump"
~~~
// Type '"Donald Trump"' is not assignable to type 'number'.(2322)
Nach dem Login kopieren

C/C のような言語をご存知の場合、そこでは型が int age として定義されています。同様に、TypeScript では、let age:number; のように、コロン記号に続く変数名の後に型を定義します。このようにして、JavaScript の構文を変更せずに TypeScript を詰め込むだけです。最初にお伝えしたのは、TypeScript は型だけを備えた単なる JavaScript ではありません。 typescript の構文には焦点を当てません。この記事の範囲外です。

JS であれば、年齢を自分の名前、配列、さらには関数に割り当てて何でもできますが、TS では、一度数値として生成されると、数値のままになります。 、他には何もありません。これを実行すると、すぐにエラーが発生しますが、JS では、関数を割り当てずに age を呼び出したり、.length プロパティにアクセスしたりするなど、不正なことをしていない限り、許容されます。関数。

最初は、JS から TS に切り替える価値がないと思われるかもしれませんが、一度完全に理解すると、この機能のためだけに JS でコーディングする必要はなくなります。

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
Nach dem Login kopieren

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.
Nach dem Login kopieren

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;
    }
}
Nach dem Login kopieren

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);
}
Nach dem Login kopieren

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);
Nach dem Login kopieren

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;

}

Nach dem Login kopieren

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.

Das obige ist der detaillierte Inhalt vonWarum sollten Sie TypeScript lernen und JavaScript aufgeben? TypeScript vs. JavaScript. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage