The difference between TypeScript and JavaScript (for an introduction to TypeScript 10000 words, it's enough to understand TS)

Keywords: Javascript Front-end TypeScript

TypeScript is a superset of JavaScript and supports ECMAScript 6 standard( ES6 tutorial ). TypeScript is a free and open source programming language developed by Microsoft. TypeScript is designed to develop large-scale applications. It can be compiled into pure JavaScript, and the compiled JavaScript can run on any browser.

TypeScript is a language extension that adds features to JavaScript. Added features include:

  • Type annotation and compile time type checking
  • Type inference
  • Type Erasure
  • Interface
  • enumeration
  • Mixin
  • Generic Programming
  • Namespace
  • tuple
  • Await 

Reverse ported from ECMA 2015:

  • class
  • modular
  • Arrow syntax for lambda functions
  • Optional and default parameters

TypeScript   Differences with JavaScript

TypeScript is a superset of JavaScript and extends the syntax of JavaScript. Therefore, existing JavaScript code can work with TypeScript without any modification. TypeScript provides static type checking at compile time through type annotation.

TypeScript can handle existing JavaScript code and compile only the TypeScript code.

  First TypeScript instance:

const greet : string = "Hello World!"
console.log(greet)

For the convenience of demonstration, all the examples in this article are running in vue3 project.

TypeScript basic syntax

The first TypeScript program (the following code demonstration omits the < script > tag and does not show the console screenshot)

<script lang="ts">
  const greet : string = "hello world!"
  console.log(greet);
</script>

 

Compare JavaScript code

const greet = "hello world!"
console.log(greet);

The reserved words in TypeScript are basically the same as those in JavaScript

TypeScript ignores spaces, tabs, and line breaks that appear in the program. Spaces and tabs are often used to indent code to make it easy to read and understand. TypeScript distinguishes between uppercase and lowercase characters. Each instruction line is a statement. You can use semicolons or not. Semicolons are optional in TypeScript and are recommended. Comments are consistent with JavaScript.

TypeScript base type

Any (any type): variables declared as any can be given any type of value.

Number (number type): double precision 64 bit floating-point value. It can be used to represent integers and fractions.

String (string type): a character series that uses single quotation marks (') or double quotation marks (") to represent the string type. Back quotation marks (`) define multiline text and embedded expressions.

Boolean (boolean type): indicates logical values: true and false.

Array type, tuple.

enum (enumeration type): an enumeration type is used to define a collection of values.

void: used to identify the type of return value of a method, indicating that the method has no return value.

null: indicates that the object value is missing.

Undefined: used to initialize a variable to an undefined value.

Never: never is a subtype of other types (including null and undefined), representing values that never appear.

Any

Arbitrary value is a data type used by TypeScript for variables with ambiguous type during programming. It is commonly used in the following cases.

1. When the value of variables will change dynamically, such as input from users, any value type can make these variables skip the type check in the compilation stage. The example code is as follows:

let flag: any = 1;    // Number type
flag = 'my name is leo';    // String type
flag = true;    // Boolean type

2. When defining an array for storing various types of data, the example code is as follows:

let list: any[] = ['leo',25,true];
list[1] = 'lion';

Null and Undefined

Null. In JavaScript, null means "nothing". Null is a special type with only one value. It means an empty object reference. Use typeof to detect null and return object.

Undefined. In JavaScript, undefined is a variable with no value set. typeof a variable with no value will return undefined. Null and undefined are any other types (including void) The subtype of can be assigned to other types, that is, other types can be converted to these two types, such as string type. At this time, the assigned type will become null or undefined.

let num: number;
num = 1; // Correct operation
num = undefined;    // The operation is correct, and it is of undefined type at this time
num = null;    // Run correctly, null type at this time

Never

Never is a subtype of other types (including null and undefined) and represents a value that will never appear. This means that variables declared as never can only be assigned by never. In functions, it usually throws an exception or cannot be executed to the termination point (such as infinite loop). The example code is as follows:

let n: never;
let num: number;

// Operation error, numeric type cannot be converted to never type
n = 123;

// If the operation is correct, the never type can be assigned to the never type
n = (()=>{ throw new Error('exception')})();

// If the operation is correct, the never type can be assigned to the numeric type
num = (()=>{ throw new Error('exception')})();

// A function with a return value of never can throw an exception
function error(message: string): never {
    throw new Error(message);
}

// A function with a return value of never can be an end point that cannot be executed
function loop(): never {
    while (true) {}
}

TypeScript variable declaration

Naming rules for TypeScript variables:

1. Variable names can contain numbers and letters.

2. Except underline  _  And dollars  $  The symbol cannot contain other special characters, including spaces.

3. Variable names cannot start with numbers.

Here are four ways to declare variables

//var [variable name]: [type] = value; declare the type and initial value of the variable
var uname:string = "leo";

//var [variable name]: [type]; declare the type of the variable, but there is no initial value, and the variable value will be set to undefined
var uname:string;

//var [variable name] = value; declare the variable and the initial value, but do not set the type. The variable can be of any type
var uname = "leo";

//var [variable name]; the declared variable has no type and initial value. The type can be any type. The default initial value is undefined
var uname;

//Summary: when declaring, if there is no type, the type is any; if there is no initial value, the initial value is undefined

example:

var uname:string = "leo";
var age:number = 25;

//Corresponding js
var uname = "leo";
var age = 25;

TypeScript follows strong types. If different types are assigned to variables, there will be compilation errors, while JavaScript will not, because it is a weakly typed language. The following example:

var num:number = "leo"     // Compilation error

//Corresponding js
var num = 100
num = "leo"     // Compile without error

Type inference

When the type is not given, the TypeScript compiler uses type inference to infer the type. If the type cannot be inferred due to the lack of declaration, its type is regarded as the default dynamic any type.

var num = 100;    // Type inferred as number
num = "leo";      // Compilation error, equivalent to the above example var num:number = "leo"

Variable scope

TypeScript has the following scopes:

global scope   − global variables are defined outside the program structure and can be used anywhere in your code.

Class scope   − this variable can also be called   Field. A class variable is declared in a class, but outside the method of the class. The variable can be accessed through the class object. Class variables can also be static, and static variables can be accessed directly through the class name.

Local scope   − local variable, which can only be used in a code block (such as a method) that declares it.

For example:

var global_num = 10          // global variable
class Person { 
   age = 18;                 // Instance variable
   static score = 100;       // Static variable
   eat():void { 
      var food = 'apple';    // local variable
   } 
}

console.log("The global variable is: " + global_num)  
console.log(Person.score)    // Static variables, accessed directly through the class name
var person = new Person(); 
console.log("Instance variable: " + person.age)

The operators, conditional statements and loops of TypeScript are basically consistent with those of JavaScript.

TypeScript function

function function_name()
{
    // Execute code
}

//Call function
function_name()

Function return value  

The function return value of TypeScript is slightly different from that of JavaScript. Format of return value of TypeScript function:

function function_name():return_type { 
    // sentence
    return value; 
}

//Compared with js, the return value of ts function needs to specify return_type returns the type of the value.

Examples are as follows:

//ts
function greet():string { // Returns a string
    return "Hello World!" 
}

//js
function greet() {
    return "Hello World!" 
}

Function with parameters

The syntax format is as follows:

function func_name( param1 [:datatype], param2 [:datatype]) {   //datatype is the parameter type
     //Execute code  
}

example:

//ts
function add(x: number, y: number): number {  //The return value of the function is number, and the data type of the parameter is number
    return x + y;
}

//js
function add(x, y) {
    return x + y;
}

Optional and default parameters

Optional parameters. In the TypeScript function, if we define several parameters, we must pass in several parameters. Unless these parameters are set to optional, the optional parameters are identified by a question mark?.

function fullName(firstName: string, lastName: string) {  //The calling function must pass in two parameters, otherwise an error will be reported
    return firstName + " " + lastName;
}
 
let name1 = buildName("leo");                  // Error, missing parameter
let name2 = buildName("leo", "lion", "gao");   // Error, too many parameters
let name3 = buildName("leo", "lion");          // correct

After modifying to optional parameter

function fullName(firstName: string, lastName?: string) { //At this time, lastName is an optional parameter and is not required
    if(lastName){
        return firstName + " " + lastName;
    }else {
        return firstName;
    }

}
 
let name1 = buildName("leo");                  // correct
let name2 = buildName("leo", "lion", "gao");   // Error, too many parameters
let name3 = buildName("leo", "lion");          // correct

//When setting optional parameters for the ts function, you can only transfer less, not more. In contrast, the parameters of the js function can be transferred more, and the parameters are taken in order.

Default parameter: you can set the default value of the parameter. In this way, if you do not pass in the value of the parameter when calling the function, the default parameter will be used. The syntax format is:

function function_name(param1[:type],param2[:type] = default_value) {
      //Execute code
}

//default_value is the default value. When the parameter is not passed in, the default value is taken.

Note: parameters cannot be set to both optional and default.  

The parameter lastName of the following instance function has a default value of 'lion', which is used if no parameter is passed in when calling the function:

function fullName(firstName:string,lastName:string = 'lion') {  
    console.log(firstName + " " + lastName); 
}

fullName('leo')         //leo lion, lastName takes the default value
fullName('leo','gao')   //leo gao

Remaining parameters

In one case, we don't know how many parameters to pass into the function. At this time, we can use the remaining parameters to define. The residual parameter syntax allows us to pass an indefinite number of parameters as an array.

function fullName(firstName: string, ...restOfName: string[]) {
    return firstName + " " + restOfName.join(" ");
}
  
let uname = fullName("leo", "lion", "ggj", "gao");

Anonymous function

An anonymous function is a function without a function name. Anonymous functions are declared dynamically when the program is running. Except that there is no function name, other functions are the same as standard functions. We can assign an anonymous function to a variable, and this expression becomes a function expression.

var greet = function() {  //Anonymous function without parameters
    return "hello world!";  
} 
console.log(msg())


var add = function(a,b) {  //Anonymous function with parameters
    return a + b;  
} 
console.log(add(2,3))

Anonymous function self call

(function () { 
    var str = "Hello World!";   
    console.log(str)     
 })()

Constructor

TypeScript also supports the use of JavaScript's built-in constructor Function() to define functions:

var res = new Function ([arg1[, arg2[, ...argN]],] functionBody)
var myFunction = new Function("a", "b", "return a * b"); 
var x = myFunction(4, 3); 
console.log(x);

Arrow function

( [param1, parma2,...param n] )=>statement;
var add = (x:number)=> {    
    x = 10 + x 
    console.log(x)  
} 
foo(100)

We can infer the parameter type within the function without specifying the parameter type of the function:

var func = (x)=> { 
    if(typeof x=="number") { 
        console.log(x+" It's a number") 
    } else if(typeof x=="string") { 
        console.log(x+" Is a string") 
    }  
} 
func(12) 
func("Tom")

  More examples

var display = x => {      //A single parameter () is optional
    console.log("Output as "+x) 
} 
display(12)


var disp =()=> {     //Empty parentheses can be set when there are no parameters
    console.log("Function invoked"); 
} 
disp();

function overloading

Overloading means that the method name is the same, but the parameters are different, and the return type can be the same or different. Each overloaded method (or constructor) must have a unique list of parameter types.

//Parameter type and parameter quantity are different
function disp(s1:string):void; 
function disp(n1:number,s1:string):void; 
 
function disp(x:any,y?:any):void { 
    console.log(x); 
    console.log(y); 
}

The Number, String and Array type languages in TypeScript are basically consistent with JavaScript.

Map object

The map object holds key value pairs and can remember the original insertion order of keys. Any value (object or original value) can be used as a key or a value. Map is a new data structure introduced in ES6, which can be used for reference   ES6 Map and Set.

TypeScript uses the Map type and the new keyword to create a Map:

let myMap = new Map();

When initializing the Map, you can pass in key value pairs in array format:

let myMap = new Map([
    ["key1", "value1"],
    ["key2", "value2"]
]); 

let nameSiteMapping = new Map();
 
// Set Map object
nameSiteMapping.set("Google", 1);
nameSiteMapping.set("Runoob", 2);
nameSiteMapping.set("Taobao", 3);
 
// Get the value corresponding to the key
console.log(nameSiteMapping.get("Runoob"));     // 2
 
// Judge whether the Map contains the value corresponding to the key
console.log(nameSiteMapping.has("Taobao"));       // true
console.log(nameSiteMapping.has("Zhihu"));        // false
 
// Returns the number of Map object key / value pairs
console.log(nameSiteMapping.size);                // 3
 
// Delete Runoob
console.log(nameSiteMapping.delete("Runoob"));    // true
console.log(nameSiteMapping);
// Remove all key / value pairs from the Map object
nameSiteMapping.clear();             // Clear Map
console.log(nameSiteMapping);

Use for...of to iterate over Map objects.

let nameSiteMapping = new Map();
 
nameSiteMapping.set("Google", 1);
nameSiteMapping.set("Runoob", 2);
nameSiteMapping.set("Taobao", 3);
 
// key in iterative Map
for (let key of nameSiteMapping.keys()) {
    console.log(key);                  
}
 
// Iterate value in Map
for (let value of nameSiteMapping.values()) {
    console.log(value);                 
}
 
// Key = > value in iterative Map
for (let entry of nameSiteMapping.entries()) {
    console.log(entry[0], entry[1]);   
}

tuple

We know that the data types of elements in the array are generally the same (arrays of any [] type can be different). If the stored element data types are different, tuples need to be used. Different types of elements are allowed to be stored in tuples, and tuples can be passed to functions as parameters.

The syntax format for creating tuples is as follows:

var tuple_name = [value1,value2,value3,...value n]

example

//Declare a tuple and initialize
var mytuple = [10,'leo',25,true];


//You can also declare an empty tuple before initializing
var mytuple = []; 
mytuple[0] = 10
mytuple[1] = 'leo'
mytuple[2] = 25
mytuple[3] = true


//Access tuples, using indexes to access
tuple_name[index]

Tuple operation

1. push() adds an element to the tuple, which is added at the end.

2. pop() removes the element (the last one) from the tuple and returns the removed element.

var mytuple = [10,"Hello","World","typeScript"];

mytuple.push(25)  // [10,"Hello","World","typeScript",25]

mytuple.pop()  // [10,"Hello","World","typeScript"]

update tuple

Tuples are variable, which means that we can update tuples:

var mytuple = [10, "leo", "lion"]; // Create a tuple
 
// Update tuple element
mytuple[0] = 25     // [25, "leo", "lion"]

Deconstruction tuple

We can also assign tuple elements to variables, as shown below:

var user =[25,"leo"] 
var [age,uname] = user
console.log( age )       // 25
console.log( uname )     // 'leo'

Union type

Union Types can set variables to multiple types through the pipeline (|), and the value can be assigned according to the set type.

Note: only the specified type can be assigned. If other types are assigned, an error will be reported.

Type1|Type2|Type3

example

//Declare a union type
var flag:string|number|boolean

flag = 25
console.log("The number is ", flag)   // The number is 25

flag = 'leo' 
console.log("String is ", flag)   // The string is leo

flag = true 
console.log("Boolean value is ", flag)   //Boolean value is true

If other types are assigned, an error will be reported:

var flag:string|number

flag = true  //An error is reported. The union type does not include boolean

You can also use union types as function parameters:

function fullName(name:string|string[]) {  //At this time, the parameter type can be string or string array
    if(typeof name == "string") { 
        console.log(name) 
    } else {
        var i; 
        for(i = 0;i<name.length;i++) { 
        console.log(name[i])
        } 
    } 
}

fullName("leo")
fullName(["leo","lion","ggj","gao"])

You can also declare an array as a union type:

var arr:number[]|string[];  //Number array or string array

Interface

An interface is a declaration of a series of abstract methods and a collection of method features. These methods should be abstract and need to be implemented by specific classes. Then a third party can call these abstract methods to let specific classes execute specific methods.

The TypeScript interface is defined as follows:

interface interface_name {

}

example

In the following example, we define an interface IPerson, and then define a variable customer, whose type is IPerson. Customer implements the properties and methods of the interface IPerson.

interface IPerson { 
    firstName:string, 
    lastName:string, 
    sayHi: ()=>string 
} 

//Implementation interface
var customer:IPerson = { 
    firstName:"Tom",
    lastName:"Hanks", 
    sayHi: ():string =>{return "Hi there"} 
}

//Implementation interface
var employee:IPerson = { 
    firstName:"Jim",
    lastName:"Blakes", 
    sayHi: ():string =>{return "Hello!!!"} 
}

Union type and interface

The following example demonstrates how to use union types in an interface:

interface RunOptions { 
    program:string; 
    commandline:string[]|string|(()=>string); 
} 
 
// commandline is a string
var options:RunOptions = {program:"test1",commandline:"Hello"}; 
console.log(options.commandline)  
 
// commandline is an array of strings
options = {program:"test1",commandline:["Hello","World"]}; 
console.log(options.commandline[0]); 
console.log(options.commandline[1]);

Interface inheritance

Interface inheritance means that an interface can extend itself through other interfaces. Typescript allows interfaces to inherit multiple interfaces. Inherit use keywords   extends.

//Single interface inheritance
Child_interface_name extends super_interface_name

//Multi interface inheritance. The inherited interfaces are separated by commas.
Child_interface_name extends super_interface1_name, super_interface2_name,...,super_interfaceN_name

Single instance inheritance  

interface Person { 
   age:number 
} 
 
interface Musician extends Person { 
   instrument:string 
} 
 
var drummer = <Musician>{}; 
drummer.age = 25 
drummer.instrument = "Drums" 
console.log("Age:  "+drummer.age)
console.log("Favorite musical instrument:  "+drummer.instrument)

// Age: 25
// Favorite instrument: Drums

Multi instance inheritance

interface IParent1 { 
    v1:number 
} 
 
interface IParent2 { 
    v2:number 
} 
 
interface Child extends IParent1, IParent2 { } 
var Iobj:Child = { v1:12, v2:23} 

class

TypeScript is object-oriented JavaScript. Class describes the common properties and methods of the created object. TypeScript supports all object-oriented features, such as classes, interfaces, and so on.

The TypeScript class is defined as follows:

class class_name { 
    // Class scope
}

The keyword defining the class is class, followed by the class name. The class can contain the following modules (data members of the class):

1. Field   − fields are variables declared in the class. Fields represent data about the object.

2. Constructor   − called when the class is instantiated, memory can be allocated for the objects of the class.

3. Method   − method is the operation to be performed by the object.

Instance to create a data member of the class:

class Car { 
    // field 
    color:string; 
 
    // Constructor 
    constructor(color:string) { 
        this.color = color
    }  
 
    // method 
    show():void {
        console.log("Color is :   " + this.color) 
    } 
}

We use the new keyword to instantiate the object of the class. When the class is instantiated, the constructor will be called, for example:

var obj = new Car("blue")

Field properties and methods in the class can use  .  Number to access:

// Access properties
obj.color 

// Access method
obj.show()

Class inheritance

TypeScript supports inherited classes, that is, we can inherit an existing class when creating A class. The existing class is called A parent class, and the class that inherits it is called A child class. Class inheritance uses keywords   Extensions, subclasses can inherit everything except the private members (Methods and properties) and constructors of the parent class. TypeScript can only inherit one class at A time. It does not support inheriting multiple classes, but TypeScript supports multiple inheritance (A inherits B, B inherits C).

example

Class inheritance: the Shape class is created in the instance, and the Circle class inherits the Shape class. The Circle class can directly use the Area attribute:

class Shape { 
   Area:number 
   
   constructor(a:number) { 
      this.Area = a 
   } 
} 
 
class Circle extends Shape { 
   show():void { 
      console.log("Area of circle:  "+this.Area) 
   } 
}
  
var obj = new Circle(223); 
obj.show()        // Area of circle: 223

It should be noted that a subclass can inherit only one parent class. TypeScript does not support inheriting multiple classes, but supports multiple inheritance, as shown in the following examples:

class Root { 
   str:string; 
} 
 
class Child extends Root {} 
class Leaf extends Child {} // Multiple inheritance, inheriting the Child and Root classes

Method overrides of inherited classes

After class inheritance, subclasses can redefine the methods of the parent class. This process is called method rewriting. The super keyword is a direct reference to the parent class, which can reference the properties and methods of the parent class.

class PrinterClass { 
   doPrint():void {
      console.log("Parent class doPrint() method.") 
   } 
} 
 
class StringPrinter extends PrinterClass { 
   doPrint():void { 
      super.doPrint() // Call the function of the parent class
      console.log("Subclass doPrint()method.")   //Override the parent method here
   } 
}

static keyword

As mentioned above, the static keyword is used to define that the data members (properties and methods) of a class are static. Static members can be called directly through the class name.

class StaticMem {  
   static num:number; 
   
   static disp():void { 
      console.log("num Value is "+ StaticMem.num) 
   } 
} 

//Call static properties and methods directly through the class name
StaticMem.num = 12     // Initialize static variables
StaticMem.disp()       // Call static method

Extension: the instanceof operator is used to judge whether the object is of the specified type. If yes, it returns true; otherwise, it returns false.

class Person { } 
var obj = new Person() 
var isPerson = obj instanceof Person;    //true

Access modifier

In TypeScript, access control characters can be used to protect access to classes, variables, methods, and constructor methods. TypeScript supports 3 different access permissions.

1. public (default)  : public and can be accessed anywhere.

2,protected  : Protected and accessible by itself and its subclasses and parents.

3,private  : Private, which can only be accessed by the class where it is defined.

The following example defines two variables str1 and str2. str1 is public and str2 is private. You can access str1 after instantiation. If you want to access str2, there will be a compilation error.

class Encapsulate { 
   str1:string = "Hello" 
   private str2:string = "World"
}
 
var obj = new Encapsulate() 
console.log(obj.str1)     // Accessible 
console.log(obj.str2)   // Compilation error, str2 is a private property

Classes and interfaces

Class can implement the interface, use the keyword implements, and use the interest field as the attribute of the class.

The following example shows that the AgriLoan class implements the ILoan interface:

interface ILoan { 
   interest:number 
} 
 
class AgriLoan implements ILoan { 
   interest:number 
   rebate:number 
   
   constructor(interest:number,rebate:number) { 
      this.interest = interest 
      this.rebate = rebate 
   } 
} 
 
var obj = new AgriLoan(10,1) 
console.log("Profit is : "+obj.interest+",Draw into : "+obj.rebate )   // Profit: 10, draw: 1

TypeScript is basically consistent with the objects in JavaScript.

Namespace

One of the most explicit purposes of namespaces is to solve the problem of duplicate names. Namespace defines the visible range of an identifier. An identifier can be defined in multiple namespaces, and its meaning in different namespaces is irrelevant. In this way, any identifier can be defined in a new namespace, and they will not conflict with any existing identifier, because the existing definitions are in other namespaces.

Namespace usage in TypeScript   namespace   The syntax format is as follows:

namespace SomeNameSpaceName { 
   export interface ISomeInterfaceName {      }  
   export class SomeClassName {      }  
}

The above defines a namespace SomeNameSpaceName. If we need to call the classes and interfaces in SomeNameSpaceName externally, we need to add a namespace in the classes and interfaces   export   keyword.

To call in another namespace, the syntax format is:

SomeNameSpaceName.SomeClassName;

Summary: the above is the basic knowledge of TypeScript. You can see some differences between TypeScript and JavaScript

1. TypeScript is a superset of JavaScript, that is, you can use native JavaScript syntax in TypeScript.

2. TypeScript is a static class language (strongly typed), and type checking is performed during compilation; JavaScript is a dynamic class language (weak type), which makes type judgment at run time, which is relatively more flexible.

3. TypeScript adds void, never, any, tuples, enumerations, and some advanced types, as well as classes, interfaces, namespaces, and more object-oriented content to the basic types of JavaScript.

4. JavaScript does not have the concept of overloading. TypeScript can be overloaded.

5. TypeScript will eventually be compiled into weak type, object-based native JavaScript, and then run.

Reference link: TypeScript tutorial | rookie tutorial

Posted by firemankurt on Tue, 02 Nov 2021 08:30:25 -0700