The difference between TypeScript and JavaScript, a comprehensive interpretation of super detailed



TypeScript is a superset of JavaScript, understand the difference between TypeScript and JavaScript to choose the appropriate language.



1. TypeScript properties

TypeScript is an object-oriented programming language developed and maintained by Microsoft. It is a superset of JavaScript, which includes all the elements of JavaScript, can be loaded into JavaScript code to run, and extends the syntax of JavaScript.

推荐先精通JS的的前提下再学习TS;这样更有利于同时学习两门语言

TS is generally used for large-scale projects, just like the underlying library of WeChat applets is implemented with TS, while the WeChat applet itself, the application layer, is implemented with JS.

1.1 Features

TypeScript has the following characteristics:

  • TypeScript adds static typing, classes, modules, interfaces, and type annotations(强调代码的模块化,面向对象)

  • TypeScript is more suitable for developing large applications(大型应用=模块的集成,大型应用优先需要易于维护,小应用优先需要开发效率)

1.2 Differences

Key differences between JavaScript and TypeScript

  • TypeScript extends the JavaScript object model both in terms of the core language and in the modeling of class concepts.

  • JavaScript code can work with TypeScript without any modification, and a compiler can be used to convert TypeScript code to JavaScript.

  • TypeScript provides compile-time static type checking through type annotations.

TypeScript提供了很多数据类型,通过类型对变量进行限制,称之为类型注解,使用类型注解后,就不能够随意变更变量的类型。
项目较大时,变量类型被变更的频率就会增加,出错的概率就会提高,因此TS时强类型的面向对象的。
  • Data in TypeScript requires explicit types, JavaScript does not.

  • TypeScript provides default parameter values ​​for functions .

缺省参数使用主要规则:调用时你只能从最后一个参数开始进行省略,换句话说,如果你要省略一个参数,你必须省略它后面所有的参数。
  • TypeScript introduces the concept of "classes" that JavaScript doesn't have.

  • TypeScript introduces the concept of modules, which can encapsulate declarations, data, functions, and classes in modules.

学过.NET 的同学也许会突然发现,TS和C# 有点类似,没错;这两门语言都出自 微软之手。。

1.3 Advantages

Is TypeScript better than JavaScript?


1.3.1 Advantages of JavaScript

From what I've described, TS seems to be just a better version of JS.

So you might think that TS will replace JavaScript in the near future. No, I still believe JavaScript has a place to play.

For example, if we use TS to develop WeChat applets, it will inevitably delay the development cycle of the project, while using JS will complete it faster.

Complexity is a key factor to consider.

JavaScript 非常适合更简单的应用程序, because it works on all platforms (cross-platform) and is very lightweight. Also, the time and CPU resources required to compile TS code will be more burdensome for the project than the minimal overhead of JS.

1.3.2 Advantages of TypeScript

TypeScript has many benefits over JavaScript.

TS makes code refactoring easier and places a greater emphasis on explicit typing, allowing developers to grasp how various components interact. Since it supports compile-time debugging, there are certain benefits for teams working on large and complex applications.

Setting up TypeScript for any project is easy. Some frameworks, like Angular, use TypeScript by default. Therefore, TypeScript is superior in my opinion .

When should I migrate my project to TypeScript?

TypeScript can be used when 代码的大小、复杂性和出错率增加时specific issues need to be identified during compilation.
TypeScript also has interfaces and access modifiers that allow developers to collaborate and interact on a single code base. Therefore, it is best to use TypeScript from the beginning of the project.
But if you like frameworks like Ember.js or Glimmer.js, then you won't like TypeScript, the first choice for these frameworks is JavaScript.

2. Code comparison

typescript defines the student class

class Student{
    
    
   name:string;
   age:number;
}
var s1=new Student();
s1.name="Jim";
s1.age=20;
document.write("name:"+s1.name+" age:"+s1.age);

Let's look at the JavaScript code compiled with TypeScript:

var Student = (function () {
    
    
    function Student() {
    
    
    }
    return Student;
})();
var s1 = new Student();
s1.name = "Jim";
s1.age = 20;
document.write("name:" + s1.name + " age:" + s1.age);

By comparing the code, the TypeScript code is more concise, better understood, and easier to maintain. Similar to C#, Java, C++.

2.1 DEMO case

Let's first look at a classic program Hello World. code show as below:

<script type="text/typescript">
  var hw:string="Hello World!";     //定义一个字符串变量
  document.write(<h1>"+hw+"</h1>);  //将结果显示在页面上,这句话是不是很熟悉呢。
</script>

We can use javascript code to run in TypeScript. The above code is written in the script tag, and the type is typescript. If you want to compile and see the results directly on the page, you also need to reference typescript.min.js and typescript.compile.min.js.

2.2 How to cite

<html>
<head>
  <title>demo</title>
</head>
<body>
  <script type="text/typescript">
     // TypeScript代码
  </script>
  <script src="lib/typescript.min.js"></script>
  <script src="lib/typescript.compile.min.js"></script>
</body>
</html>

3. Grammatical difference


3.1 Basic data types of TypeScript

The basic data types of TypeScript are boolean, number, string, array, enum, any, void.

  • Such as defining a boolean variable:
var isDone: boolean = false;
  • All values ​​in JS and TS are floating-point type, while in TS it is defined as "number" type. Declare a variable of type number:
var isNumber:number=6;
var isfloat:number=6.01;
  • Use a pair of double quotes (") or a pair of single quotes (') to denote a string
var name: string = "bob";
var family_name: string = 'Green';
  • Arrays in TypeScript are declared using "[]", the code is as follows:
var list: number[] = [1, 2, 3];
var name: string[] = ["阿龙","阿猫","阿狗"];

// 访问方式 
var list: number[] = [1, 2, 3];
alert(list[0]));

// 定义任意类型的数组,关键字为Array.
var arr:Array = [1,2,3,"a","b","c"]; // 任意类型数组
alert(arr[1]);

3.1.1 enum

Enum types are new to TypeScript, and JavaScript does not have this type. Declared with the keyword enum. The code example is as follows:

enum Color {
    
    
  Red,   //枚举元素列表
  Green,
  Blue
};
var c: Color = Color.Green;

If we have a value, but we don't know whether there is a definition in the enumeration type, we can get it in the following way, the code is as follows:

enum Color {
    
    
  Red = 1,
  Green,
  Blue
};
var colorName: string = Color[2]; //访问第二个枚举子元素Green
alert(colorName);
colorName = Color[4];
alert(colorName);

Then Green and undefined will be output. Because the value of Green is 2 and none of the enumeration definitions has a value of 4, undefined is returned.


3.1.2 Any type any

Like the default type of variables in JavaScript, references are dynamic and can be assigned any type. For example:

var notSure: any = 4;
notSure = "maybe a string instead";
notSure = false;  // 定义为boolen型

After being defined as any, it will lose the function of syntax awareness, which is equivalent to writing JavaScript. It is worth mentioning that any can be used with arrays, the code is as follows:

var list: any[] = [1, true, "free"];
list[1] = 100; //更改list[1]的值

Note, do not abuse any, if any value is specified as any type, then TypeScript will lose its meaning. A script without a type would be meaningless.

3.3.3 Type void

Void is the opposite of any. Any means any type, and void means that there is no type, that is, no type. This is used when we define a function and the function has no return value:

const consoleText = (text: string): void => {
    
    
  console.log(text);
};

Variables of void type can only be assigned as undefined and null, and other types cannot be assigned to variables of void type.

3.3.4 never type

The never type refers to the type of values ​​that never exist. It is the return value type of function expressions that always throw an exception or never return a value. When the variable is constrained by the type protection that is never true, This variable is also of type never.


This type is more difficult to understand, let's look at a few examples first:

const errorFunc = (message: string): never => {
    
    
  throw new Error(message);
};

This errorFunc function will always throw an exception, so its return value type is never, which is used to indicate that its return value will never exist.

const infiniteFunc = (): never => {
    
    
  while (true) {
    
    }
};

3.2 Definition and call of functions

The syntax for defining a function in TypeScript is:

function function_name(arg:number,arg1:number,....):return_type{
    
    
  code 函数要执行的代码;
  return data;
}

Where function is the keyword for declaring the function, function_name is the name of the custom function, arg is the parameter list, _returntype is the return value type of the function, code is the code to be executed when the function is called, use the return keyword to return data, data For the data to be returned, use "{}" brackets. The function call is very simple, the following code:

function add(x: number, y: number): number {
    
      //定义返回值为number类型的函数
    return x+y;
}
add(5,6); //调用函数
  • Anonymous function:
    An anonymous function is a function that has no name but only a body. It does not need to specify a return type. Its return value type is inferred from the return statement in the function body. The following code:
var myAdd = function(x:number, y:number) {
    
     //定义匿名函数
  return x+y;
  };
myAdd(3,4); //调用匿名函数
  • Optional and default parameters

Optional parameters: Add a question mark after the parameter name and before the colon to indicate that the parameter is optional. The following code:

function buildName(firstName: string, lastName?: string) {
    
     //lastName为可选参数
  if (lastName)
      return firstName + " " + lastName;
  else
      return firstName;
}
var result1 = buildName("Bob");  //正确调用 Bob
var result2 = buildName("Bob", "Adams"); //正确调用 Bob Adams

Default parameter: A value is given directly after the parameter name. If the value is not passed in, it will be assigned the default value. The following code:

function buildName(firstName: string, lastName = "Smith") {
    
    
  return firstName + " " + lastName;
}

var result1 = buildName("Bob");  //没有传入第二个参数,则被赋值为默认的smith,结果为:Bob Smith
var result2 = buildName("Bob", "Adams");  //结果为:Bob Adams

Note: Optional parameters and default parameters must be at the end of the parameter list.

3.3 TS classes


3.3.1 Class structure and declaration

The JavaScript language builds reusable components based on functions and the inheritance mechanism of the prototype chain. This is clumsy for object-oriented programming.

在下一代的JavaScript标准将为我们提供基于class base的面向对象的设计方式。但在TypeScript中可以使用这种方式,它将编译为目前大多数浏览器能允许的普通JavaScript代码.

So we don't have to wait for the next generation of Javascript standards to come.

Classes are the core foundation of object-oriented programming. They are a collection of attributes and methods. Classes cannot be directly referenced when writing a program. They must be instantiated before they can be used.

When creating a TypeScript class, you must use the keyword class to declare, followed by the name of the class, and then use curly braces to encapsulate the class body. The basic declaration format of a class is as follows.

class 类名{
    
    
    //类体
}

After the basic structure of the class is created, the class body can be written. The class body mainly includes the declaration and definition of attributes and methods. Of course, only attributes or methods may be defined in the class body, or even no attributes may be defined in the class body. The complete class definition format is as follows.

class 类名{
    
    
  name:string;  //定义类的属性
  fun(){
    
     //定义类的方法
           //定义该方法所要实现的功能
  }
}

  • Why can no attribute be defined?
  • A class can be inherited, and its methods and properties can be inherited in subclasses
  • An empty class that does not define any methods can be used as a generic class
  • To sum up, an empty class that does not define any methods has a value of its name

Constructor

class student{
    
      //定义student类
  name:string;  //定义类的属性
  constructor(myname:string){
    
     //定义构造函数
      this.name=myname;
  }
  study(){
    
     //定义类的方法
           //定义该方法所要实现的功能
  }
}

Classes defined in this way feel like writing C#, Java or C++ programs. Yes, TS is object-oriented.

3.3.2 Class instantiation

In general, after creating a class, you cannot directly refer to the properties and methods, you must instantiate the class, that is, create an object. Objects are created with the new keyword in TypeScript. After instantiation, use "." to access properties and methods. The example code is as follows:

class student{
    
      //定义student类
  name:string;  //定义类的属性
  constructor(myname:string){
    
     //定义带参数的构造函数
      this.name=myname;
  }
   study(){
    
     //定义类的方法
      document.write("<h1> My name is "+this.name+".</h1>");
  }
   write():string{
    
    
           return "write name:"+this.name;
  }
}

use of class

var s1=new student("Jim");
document.write("<h1>"+s1.name+"</h1>"); //获取name属性
s1.study();   // 调用study方法  
document.write("<h1>"+s1.write()+"</h1>");

3.4 Modules of TS

Let's give an example first, such as data verification. When we need to verify whether the content of user numbers is numbers or letters, we need to use regular expressions.

var lettersRegexp = / ^ [A-Za-z]+$/;

var numberRegexp = / ^ [0-9]+$/;

Data validation can improve user experience and prevent incorrect information from being entered. After learning the previous knowledge, we are likely to write the following code:

// 验证的封装
interface StringValidator {
    
      //定义验证接口
  isAcceptable(s: string): boolean;
}

var lettersRegexp = /^[A-Za-z]+$/;
var numberRegexp = /^[0-9]+$/;

class LettersOnlyValidator implements StringValidator {
    
     //实现接口
  isAcceptable(s: string) {
    
    
    return lettersRegexp.test(s);
  }
}

class ZipCodeValidator implements StringValidator {
    
       //实现接口
  isAcceptable(s: string) {
    
    
    return s.length === 5 && numberRegexp.test(s);
  }
}

// 验证的过程
var strings = ['Hello', '98052', '101'];
var validators: {
    
     [s: string]: StringValidator; } = {
    
    };
validators['ZIP code'] = new ZipCodeValidator();  //实例化类
validators['Letters only'] = new LettersOnlyValidator(); //实例化类
for(var i=0;i&ltstrings.length;i++){
    
    
    for (var name in validators) {
    
    
       document.write('"' + strings[i] + '" ' + (validators[name].isAcceptable(strings[i]) ? ' matches ' : ' does not match ') + name+"<br>"); //调用类的方法
    }
}
  • So what is the biggest problem with this code?
  • One is that it cannot be reused. The verification package interface StringValidator LettersOnlyValidator ZipCodeValidator and the verification process, that is, the following methods are in the same file, and the verification package is already reusable.
  • The other is that the interface and the two implemented classes are directly linked to the global variables. If the number is too large, it will affect the entire global variable. If the internal class of the class is separated from the internal method of the class, the module will be improved. and strengthen the object-oriented features.
  • The emergence of modules in TypeScript solves this problem for us.
  • Use the module keyword to define a module and add curly braces at the end to make it available;
  • Use the export keyword to make members of interfaces, classes, etc. visible outside the module.
module Validation {
    
       //定义模块
  export interface StringValidator {
    
      //声明接口对外部可以使用
    isAcceptable(s: string): boolean;
  }

  var lettersRegexp = /^[A-Za-z]+$/;
  var numberRegexp = /^[0-9]+$/;

  export class LettersOnlyValidator implements StringValidator {
    
      //声明类对外部可用
    isAcceptable(s: string) {
    
    
      return lettersRegexp.test(s);
    }
  }

  export class ZipCodeValidator implements StringValidator {
    
    
    isAcceptable(s: string) {
    
    
      return s.length === 5 && numberRegexp.test(s);
    }
  }
}

3.4.1 Calling of module content

In the previous section, I learned the declaration of the module, and after the module declaration is completed, we can call the module, and call the interface, class, method, etc. in the module. The calling method is simple, that is, use the module name followed by a dot to call classes, interfaces, methods, etc. The following code:



var strings = ['Hello', '98052', '101'];
var validators: {
    
     [s: string]: Validation.StringValidator; } = {
    
    };
validators['ZIP code'] = new Validation.ZipCodeValidator();  //使用模块中的类
validators['Letters only'] = new Validation.LettersOnlyValidator();
// 显示匹配结果
for(var i=0;i&ltstrings.length;i++){
    
    
  for (var name in validators) {
    
    
     document.write('"' + strings[i] + '" ' + (validators[name].isAcceptable(strings[i]) ? ' matches ' : ' does not match ') + name+"<br>"); // 使用方法
    }
}

3.4.2 Separate modules into multiple files

As our project expands, our code cannot always be written in just one file. In order to better maintain the project, we will put specific functions into a file, and then load multiple files to achieve the functions we want. Now let's split the above code into multiple files.

File 1 Validation.ts

module Validation {
    
    
  export interface StringValidator {
    
    
      isAcceptable(s: string): boolean;
  }
}

File 2 LettersOnlyValidator.ts

/// <reference path="Validation.ts" />
module Validation {
    
    
  var lettersRegexp = /^[A-Za-z]+$/;
  export class LettersOnlyValidator implements StringValidator {
    
    
      isAcceptable(s: string) {
    
    
        return lettersRegexp.test(s);
      }
  }
}

File 3 ZipCodeValidator.ts

/// <reference path="Validation.ts" />
module Validation {
    
    
  var numberRegexp = /^[0-9]+$/;
  export class ZipCodeValidator implements StringValidator {
    
    
    isAcceptable(s: string) {
    
    
      return s.length === 5 && numberRegexp.test(s);
    }
  }
}

File 4 Test.ts

/// <reference path="Validation.ts" />
/// <reference path="LettersOnlyValidator.ts" />
/// <reference path="ZipCodeValidator.ts" />

var strings = ['Hello', '98052', '101'];
var validators: {
    
     [s: string]: Validation.StringValidator; } = {
    
    };
validators['ZIP code'] = new Validation.ZipCodeValidator();
validators['Letters only'] = new Validation.LettersOnlyValidator();
for(var i=0;i&ltstrings.length;i++){
    
    
  for (var name in validators) {
    
    
     document.write('"' + strings[i] + '" ' + (validators[name].isAcceptable(strings[i]) ? ' matches ' : ' does not match ') + name+"<br>"); //调用类的方法
    }
}

Create the above four files in the project, and then we compile the project. If our code is written correctly, it can be compiled and passed.

We can see that there are documentation comments similar to C# at the beginning of the last three files,

/// < reference path=“Validation.ts” />
/// < reference path=“LettersOnlyValidator.ts” />
/// < reference path=“ZipCodeValidator.ts” />

This is to tell the TypeScript compiler which files the file depends on. If the dependent files do not exist, the compilation will fail. Of course, it's okay if we don't write it, but the compiler won't check it for us when compiling. Generally speaking, it is recommended to write it.

3.4.3 Compilation of TS

We know that .js files can be run directly in the browser, but .ts or .tsx cannot, so we need to compile it into a JS language that the browser engine can recognize when running the TS project. At the same time, in order to improve the compilation speed, we can modulecompile the stable js file in advance and put it in the project, so that the next compilation will directly skip the compilation of the nodule. When referring to compiled JavaScript files, we need to pay attention to the order. Taking the above code as an example, we refer to it in the Html code.

<script src="Validation.js" type="text/javascript"/>
<script src="LettersOnlyValidator.js" type="text/javascript"/>
<script src="ZipCodeValidator.js" type="text/javascript"/>
<script src="Test.js" type="text/javascript"/>

I admire your courage after reading this, remember to like and follow~~
更新时间:2022年12月3日20:11:12
Article catalog:

Guess you like

Origin blog.csdn.net/gao511147456/article/details/125809525