SoFunction
Updated on 2025-04-07

Comprehensive interpretation of the difference between TypeScript and JavaScript

feature JavaScript TypeScript
Type system Weak type Strong type
Static type checking none have
Optional type annotation none have
Type inference have have
interface none have
inherit Prototype-based inheritance Class-based inheritance
Generics none support
Support decorators none support
Compile-time type check Not supported support
Compiled code readability high Low
Community activity Very high Very high

Summarize:

TypeScript is a superset of JavaScript. It adds strong types, interfaces, classes, generics and other features based on JavaScript, and provides tools such as static type checking, allowing developers to write code more safe, efficient and reliable. Compared with JavaScript, TypeScript has the advantages of stronger type systems, stricter type checking, better code readability and maintenance. In addition, TypeScript has a very high community activity, and it is adopted by more and more developers and companies.

characteristic

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

It is recommended to learn TS first if you are proficient in JS; this is more conducive to learning two languages ​​at the same time.

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

1.1 Features

TypeScript has the following features:

  • TypeScript adds static types, classes, modules, interfaces, and type annotations(emphasizes the modularity of code and is object-oriented)

  • TypeScript is more suitable for developing large-scale applications(Large applications = module integration, large applications require ease of maintenance, small applications require development efficiency)

1.2 Differences

Key Differences between JavaScript and TypeScript

  • TypeScript extends the JavaScript object model from the core language aspect and the molding of class concepts.

  • JavaScript code can work with TypeScript without any modifications, and you can use the compiler to convert TypeScript code to JavaScript.

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

TypeScript provides many data types, and restricts variables through types, which are called type annotations. After using type annotations, the types of variables cannot be changed at will. When the project is large, the frequency of the variable type being changed will increase, and the probability of error will increase, so strongly typed object-oriented in TS.

  • Data requirements in TypeScript are of clear types, but JavaScript does not.

  • TypeScript provides default parameter values ​​for functions.

The default parameters use the main rule: when called, you can only omit the last parameter. In other words, if you want to omit a parameter, you must omit all the parameters after it.

  • TypeScript introduces the concept of "classes" that are not available in JavaScript.

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

Students who have studied .NET may suddenly realize that TS and C# are a bit similar, yes; both languages ​​are from Microsoft. .

1.3 Advantages

Is TypeScript better than JavaScript?

1.3.1 Advantages of JavaScript

According to my description, TS seems to be just a better version of JS.

So you might think TS will replace JavaScript in the near future. Actually, I still believe that JavaScript will work.

For example, when we use TS to develop WeChat mini programs, it will inevitably delay the project development cycle, while using JS will be completed faster.

Complexity is a key factor to consider.

JavaScript is perfect for simpler applications, because it can run on all platforms (cross-platform) and is very lightweight. In addition, compared with the minimum overhead of JS, the time and CPU resources required to compile TS code will be more troublesome for the project.

1.3.2 Advantages of TypeScript

TypeScript has many benefits compared to JavaScript.

TS makes code refactoring easier and emphasizes explicit types, allowing developers to master the way various components interact. Because it supports compile-time debugging, it has some benefits for teams dealing with large and complex applications.

Setting up TypeScript for any project is easy. Some frameworks, such as Angular, use TypeScript by default. Therefore, in my opinionTypeScript is better

When should I migrate my project to TypeScript?

whenWhen the size, complexity and error rate of code increase, TypeScript can be used when you need to determine specific problems during the compilation process.
TypeScript also has interfaces and access modifiers, allowing developers to collaborate and interact on a single code base. Therefore, it is best to use TypeScript at the beginning of the project.
But if you like frameworks like or such, you won't like TypeScript, and the preferred framework is JavaScript.

2. Code comparison

typescript defines student classes

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

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

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

By comparing the code, TypeScript code is simpler, 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. The code is as follows:

<script type="text/typescript">
  var hw:string="Hello World!";     //Define a string variable  (<h1>"+hw+"</h1>);  //Show the results on the page. Isn’t this sentence very familiar?</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 directly compile on the page and see the results, you also need to reference and.

2.2 How to quote

<html>
<head>
  <title>demo</title>
</head>
<body>
  <script type="text/typescript">
     // TypeScript code  </script>
  <script src="lib/"></script>
  <script src="lib/"></script>
</body>
</html>

3. Grammar differences

3.1 Basic data types of TypeScript

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

  • For example, define a boolean variable:
var isDone: boolean = false;
  • All values ​​in JS and TS are floating-point types, and are defined as "number" types in TS. 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 represent a string
var name: string = "bob";
var family_name: string = 'Green';
  • Arrays in TypeScript are declared using "[]", and the code is as follows:
var list: number[] = [1, 2, 3];
var name: string[] = ["Aaron","Ah Cat","Adog"];
// Access methodvar list: number[] = [1, 2, 3];
alert(list[0]));
// Define an array of any type, with the keyword Array.var arr:Array = [1,2,3,"a","b","c"]; // Array of any typealert(arr[1]);

3.1.1 enum

The enum type is newly added in TypeScript, but there is no such type in JavaScript. Declare with the keyword enum. The code example is as follows:

enum Color {
  Red, //Enumer element list  Green,
  Blue
};
var c: Color = ;

If we have a numeric value, but we don't know if there is a definition in the enum type, we can obtain it in the following way, the code is as follows:

enum Color {
  Red = 1,
  Green,
  Blue
};
var colorName: string = Color[2]; //Access the second enumeration child element Greenalert(colorName);
colorName = Color[4];
alert(colorName);

Then Green and undefined will be output. Because Green's value is 2, and no enum defined value is 4, undefined is returned.

3.1.2 Any type any

Like the default type of variables in JavaScript, the reference is dynamic and can be assigned to any type. For example:

var notSure: any = 4;
notSure = "maybe a string instead";
notSure = false;  // Defined asboolentype

After defining as any, the syntax-aware function will be lost, 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; //Changelist[1]Value of

Note that don't abuse any, if any value is specified as any type, TypeScript will lose its meaning. There would be no point in losing script with type.

3.3.3 Type void

void and any , whereas any represents any type, void represents no arbitrary type, which means that no type is not. This will be used when we define a function and the function does not return value:

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

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

3.3.4 never type

The never type refers to the types of values ​​that never exist. It is the return value type of function expressions that always throw exceptions or do not have a return value at all. When a variable is constrained by the type protection of never true, the variable is also a never type.

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

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

The errorFunc function always throws an exception, so its return value type is never, which indicates that its return value never exists.

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

3.2 Function definition and call

The syntax for defining a function in TypeScript is:

function function_name(arg:number,arg1:number,....):return_type{
  code The code to execute the function;
  return data;
}

where function is the keyword that declares 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, data is the data to be returned, and it must be enclosed with "{}". The call to the function is very simple, as follows:

function add(x: number, y: number): number {  //Define a function with a return value of number type    return x+y;
}
add(5,6); //Calling functions
  • Anonymous functions:
    Anonymous functions are functions with no names but only bodies. They do not need to specify a return type. The return value type is inferred from the return statement inside the function body. The following code:
var myAdd = function(x:number, y:number) { //Define anonymous functions  return x+y;
  };
myAdd(3,4); //Call anonymous functions
  • Optional and default parameters

Optional parameters: Adding a question mark before the parameter name indicates that the parameter is optional. The following code:

function buildName(firstName: string, lastName?: string) { //lastName is optional parameter  if (lastName)
      return firstName + " " + lastName;
  else
      return firstName;
}
var result1 = buildName("Bob");  //Call Bob correctlyvar result2 = buildName("Bob", "Adams"); //Call correctly Bob Adams

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

function buildName(firstName: string, lastName = "Smith") {
  return firstName + " " + lastName;
}
var result1 = buildName("Bob");  //No second parameter is passed in, then the value is assigned to the default smith, and the result is: Bob Smithvar result2 = buildName("Bob", "Adams");  //The result is:Bob Adams

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

3.3 TS class

3.3.1 Class Structure and Declaration

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

The next generation of JavaScript standards will provide us with object-oriented design methods based on class base. But this method can be used in TypeScript, which will compile into normal JavaScript code that most browsers currently allow.

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

Classes are the core basis of object-oriented programming and are a collection of properties and methods. Classes cannot be referenced when writing programs and must be instantiated before they can be used.

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

class Class Name{
    //Class}

After creating the basic structure of the class, you can write the class body. The class body mainly includes the declaration and definition of attributes and methods. Of course, it is possible to only define attributes or only methods in the class body, and even no attributes can be defined in the class body. The complete class definition format is as follows.

class Class Name{
  name:string;  //Define the properties of the class  fun(){ //Define the method of class           //Define the function to be implemented by this method  }
}
  • Why can you not define any attributes?
  • Classes can be inherited, and its methods and properties can be inherited in subclasses
  • Empty classes with no method defined can be used as generic classes
  • In summary, empty classes with no method defined have their names that have value

Constructor

class student{  //Define student class  name:string;  //Define the properties of the class  constructor(myname:string){ //Define the constructor      =myname;
  }
  study(){ //Define the method of class           //Define the function to be implemented by this method  }
}

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

3.3.2 Instantiation of Class

Generally speaking, after creating a class, the attributes and methods cannot be directly referenced. The class must be instantiated, that is, an object must be created. Use the new keyword to create objects in TypeScript. After instantiation, the properties and methods are accessed through "." The example code is as follows:

class student{  //Define student class  name:string;  //Define the properties of the class  constructor(myname:string){ //Define constructor with parameters      =myname;
  }
   study(){ //Define the method of class      ("<h1> My name is "++".</h1>");
  }
   write():string{
           return "write name:"+;
  }
}

Use of classes

var s1=new student("Jim");
("<h1>"++"</h1>"); //Get name attribute();   // Call study method("<h1>"+()+"</h1>");

3.4 TS module

Let’s first give an example, such as data verification. When we need to verify whether the content of the user’s number is a number or a letter, we need to use regular expressions.

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

Data verification can improve user experience to prevent incorrect input information. After learning the previous knowledge, we are likely to write the following code:

// Verified encapsulationinterface StringValidator {  //Define the verification interface  isAcceptable(s: string): boolean;
}
var lettersRegexp = /^[A-Za-z]+$/;
var numberRegexp = /^[0-9]+$/;
class LettersOnlyValidator implements StringValidator { //Implement the interface  isAcceptable(s: string) {
    return (s);
  }
}
class ZipCodeValidator implements StringValidator {   //Implement the interface  isAcceptable(s: string) {
    return  === 5 && (s);
  }
}
// Verification processvar strings = ['Hello', '98052', '101'];
var validators: { [s: string]: StringValidator; } = {};
validators['ZIP code'] = new ZipCodeValidator();  //Instantiated classvalidators['Letters only'] = new LettersOnlyValidator(); //Instantiated classfor(var i=0;i&;i++){
    for (var name in validators) {
       ('"' + strings[i] + '" ' + (validators[name].isAcceptable(strings[i]) ? ' matches ' : ' does not match ') + name+"
"); //Calling the method of the class    }
}
  • So what is the biggest problem with this code?
  • One is a verified encapsulationinterface StringValidator LettersOnlyValidator ZipCodeValidator and the verification process is the following method in the same file, the verification packaging can already be reused.
  • The other is that the interface and the two implemented classes are directly attached to the global variables. If there are too many, it will affect the entire global variable. If the internal class of the class and the internal methods of the class are separated, modularity will be improved and object-oriented features will be strengthened.
  • The emergence of modules in TypeScritp solves this problem.
  • Use the module keyword to define the module and add curly braces at the end to use it;
  • Use the export keyword to make interfaces, classes and other members visible outside the module.
module Validation {   //Define module  export interface StringValidator {  //Declare the interface to be used externally    isAcceptable(s: string): boolean;
  }
  var lettersRegexp = /^[A-Za-z]+$/;
  var numberRegexp = /^[0-9]+$/;
  export class LettersOnlyValidator implements StringValidator {  //Declaration class is available to external    isAcceptable(s: string) {
      return (s);
    }
  }
  export class ZipCodeValidator implements StringValidator {
    isAcceptable(s: string) {
      return  === 5 && (s);
    }
  }
}

3.4.1 Calling of module content

In the previous section, I learned about the declaration of a module. After the declaration of the module is completed, we can call this module, calling interfaces, classes, methods, etc. in the module. The calling method is simple, which is to use a dot to call classes, interfaces, methods, etc. after the module name. The following code:

var strings = ['Hello', '98052', '101'];
var validators: { [s: string]: ; } = {};
validators['ZIP code'] = new ();  //Use the class in the modulevalidators['Letters only'] = new ();
// Show matching resultsfor(var i=0;i&;i++){
  for (var name in validators) {
     ('"' + strings[i] + '" ' + (validators[name].isAcceptable(strings[i]) ? ' matches ' : ' does not match ') + name+"<br>"); // How to use    }
}

3.4.2 Separating modules to multiple files

As our project expands, it is impossible for our code to be written in just one file. To better maintain the project, we will put specific functions into one file and then load multiple files to implement the functions we want to need. Now let's divide the above code into multiple files.

File One

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

File Two

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

File Three

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

File 4

/// &lt;reference path="" /&gt;
/// &lt;reference path="" /&gt;
/// &lt;reference path="" /&gt;
var strings = ['Hello', '98052', '101'];
var validators: { [s: string]: ; } = {};
validators['ZIP code'] = new ();
validators['Letters only'] = new ();
for(var i=0;i&amp;;i++){
  for (var name in validators) {
     ('"' + strings[i] + '" ' + (validators[name].isAcceptable(strings[i]) ? ' matches ' : ' does not match ') + name+"&lt;br&gt;"); //Calling the method of the class    }
}

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

We can see that the following three files have document comments similar to C# at the beginning.

/// < reference path=“” />
/// < reference path=“” />
/// < reference path=“” />

This tells the TypeScript compiler which files the file depends on. If the dependent file does not exist, the compilation will not be passed. Of course, it is OK for us not to write, but the compiler will not help us check when compiling. Generally speaking, it is recommended to write it.

3.4.3 TS compilation

We know that .js files can be run directly in the browser, while .ts or .tsx cannot do it, so when we run the TS project, we need to compile it into a JS language that the browser engine can recognize. At the same time, in order to improve the compilation speed, we can make stablemoduleCompile it into a js file in advance and put it in the project, so that the compilation of the node will be directly skipped for the next time you compile. When referencing compiled JavaScript files, we need to be careful of the good order. The above code is used as an example, we reference it in the Html code like this.

<script src="" type="text/javascript"/>
<script src="" type="text/javascript"/>
<script src="" type="text/javascript"/>
<script src="" type="text/javascript"/>

This is the end of this article about comprehensively interpreting the difference between TypeScript and JavaScript. For more information about the differences between TypeScript and JavaScript, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!