I’m a front-end beginner and new to TypeScript. Compared to JavaScript, TypeScript is more rigorous and produces cleaner code. Hope to see friends help.
1. The disadvantage of JavaScript
JavaScript is a weakly typed, weakly typed definition language: a language in which data types can be ignored. In contrast to strongly typed languages, a variable can be assigned values of different data types. Strong typing languages may be slightly slower than weak typing languages, but the rigor that comes with strong typing languages can effectively prevent many errors. Here’s a simple example:
let num=0;
console.log(num);
num="123";
console.log(num);
num=true;
console.log(num);
num= new Date(a);console.log(num);
Copy the code
Let me explain the code. Assigning different data types to a variable and printing them out in console.log yields the following output
It is not hard to see that when we first create a variable num of let type, we can assign it various types: numeric type, string, Boolean type, object type, so we can infer that JavaScript is a weakly typed language.
Here’s another example of a function that calculates the area of a rectangle:
function area(w,h){
console.log(w,h);
return w*h;
}
console.log(area());
console.log(area(1));
console.log(area(1.'a'));
console.log(area(1.3));
Copy the code
The following information is displayed:
function area(w,h){
if(arguments.length<2)
{
throw new Error('Please pass two arguments')
return;
}
if(typeofw ! ='number'|| typeofh! ='number') {throw new Error('Wrong parameter type');
return;
}
return w*h;
}
console.log(area(1.3));
Copy the code
TypeScript rigor
We write the same function in typescript
function Area(w:number,h:number) :number {
console.log(w,h);
return w*h;
}
console.log(Area());
Copy the code
conclusion
TypeScript and JavaScript are two popular scripting languages in project development, and TypeScript is a superset of JavaScript. TypeScript is more rigorous than JavaScript and makes code more convenient and concise.