The necessity and use of typescript | JD Cloud technical team

1 Introduction

As a front-end language, Javascript was originally only used to write pages, and now it has become almost ubiquitous in mobile terminals, back-end services, neural networks, etc. Such a broad application field has higher requirements for the security, robustness and maintainability of the language. Although the ECMAScript standard has made great progress in recent years, it still has no achievements in type checking. In this case TypeScript came into being.

2 Why use TypeScript

In the development process of JavaScript, I believe that the following scenarios are often encountered:

  1. Scenario 1: You need to call a function function funcName(paramA,paramB,paramC,paramD){…} developed by someone else, but unfortunately, this guy did not leave any comments, in order to figure out the type of the parameters, you have to be hard Scalp to read the logic inside;
  2. Scenario 2: In order to ensure the robustness of the code, you have responsibly made various assumptions on each input parameter of the function, causing more than half of the code in the function to judge the parameters (type, number, etc.);
  3. Scenario 3: The boss is very optimistic about you and asks you to maintain an important underlying class library. You have exhausted your efforts to optimize a parameter type. Before submitting the code, you don’t know how many places are called. Do you feel chills down your spine?
  4. etc…

The above situation boils down to the fact that JavaScript is a dynamic weakly typed language, which is very tolerant to the type of variables, and does not establish a structured contract between these variables and their callers. If you develop in an environment without type constraints for a long time, it will cause the lack of "type thinking" and develop bad programming habits. This is also one of the shortcomings of front-end development. Therefore, using TypeScript is a great choice for front-end developers. urgent and necessary.

There are other benefits to using TypeScript as well. For example, Visual Studio Code has powerful auto-completion, navigation, and refactoring functions, which allow interface definitions to directly replace documents, improve development efficiency, and reduce maintenance costs. More importantly, TypeScript can help the team reshape "type thinking", enabling front-end developers to transform from code writers to code designers.

If JavaScript is a wild horse, then TypeScript is the reins of that wild horse. As a knight, you can naturally open your arms and let yourself go, but if you are not skilled, you may fall badly. But if you hold the reins, you can walk in the garden, and you can whip the horse. This is the value of TypeScript, it will make you more stable and go further on the road of front-end development.

3 What is TypeScript

What is TypeScript? According to the official definition, it is a superset of JavaScript with a type system that can be compiled into pure JavaScript. There are three points to note here:

  1. Type checking, TypeScript will perform strict static type checking during the compilation phase, which means that you can find some errors during the code writing phase, without having to bring them online to run;
  2. Language extensions: TypeScript will include features from ECMAScript 6 and future proposals, such as asynchronous operations and decorators, and will borrow certain features from other languages, such as interfaces and abstract classes;
  3. Tool attributes: TypeScript can be compiled into standard JavaScript and can run on any browser and operating system without any runtime overhead. From this perspective, TypeScript is more like a tool than an independent language

4 Basic use of TypeScript

4.1 Basic types

Ts contains types as follows:

  1. Number type (number): used to identify the double-precision 64 as a floating-point value, including integers, floating-point numbers, etc., there is no separate integer and floating-point type;
  2. String (string): A series of characters, use single quotes (') or double quotes (") to indicate the string type. Backticks (`) to define multi-line text and embedded expressions;
  3. Boolean (boolean): the value is only true and false;
  4. Array: No keyword, declare variable:
let arr: number[] = [1, 3]  
let arr:Array<number> = [1,2]

5. Tuple: No keyword, the tuple type is used to represent an array with known number and type of elements. The type of each element does not have to be the same, but the type of the corresponding position needs to be the same;

let x: [string, number];
x = ['Runoob', 1];    // 运行正常
x = [1, 'Runoob'];    // 报错
console.log(x[0]);    // 输出 Runoob
x.push(33)
console.log(x[2]) // 报错
// 注意x可以继续push多个字段,但是无法访问

6. Enumeration (enum): The enumeration type is used to define a collection of types

Numeric enums: By default, the first enumeration value is 0, and each subsequent value is incremented by 1. However, you can change the number associated with any enumeration member through a specific assignment. In the following example, we start from 3 starts to increase sequentially

enum Color {
Red,  // 0
Green,  // 1
Blue // 2
};
let c: Color = Color.Blue;
console.log(c);    // 输出 2
console.log(Color[0]) // 输出Red
enum Color1 {
Red = 3, // 3
Green, // 4
Blue // 5
}

7. void: used to identify the return value of the method, indicating that there is no return value

8.null: the identification object value is missing;

9.undefined: Used to initialize variables to an undefined value

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

11. Object: object represents a non-primitive type, that is, a type other than number, string, boolean, symbol, null or undefined.

12. any: any value is a data type used by TypeScript for variables with ambiguous types during programming; (note: don’t use any lightly, using any has the same effect as using javascript)

It is commonly used in the following three situations:

  • When the value of a variable changes dynamically, such as from user input, any value type allows these variables to skip type checking during compilation;
  • Arbitrary values ​​allow optional inclusion or removal of type checking at compile time when rewriting existing code;
  • When defining arrays that store data of various types

13. Joint type: variables can be set to multiple types through the pipeline (|), and the value can be assigned according to the set type when assigning

var val:string|number 
val = 12 
console.log("数字为 "+ val) 
val = "Runoob" 
console.log("字符串为 " + val)

4.2 Functions

// 包含两个number类型参数和返回值,不能直接return。必须return一个数字
function add(x: number, y: number): number {
    return x + y;
}
 // 可选参数, (这里没写返回值,利用了typeScript的类型推断能力)
function buildName(firstName: string, lastName?: string, a?:number) {
    if (lastName)
        return firstName + " " + lastName;
    else
        return firstName;
}
// 参数默认值
function buildName(firstName: string, lastName: string = 'default_name') {
    return firstName + " " + lastName;
}
// 有一种情况,我们不知道要向函数传入多少个参数,这时候我们就可以使用剩余参数来定义,
// 剩余参数语法允许我们将一个不确定数量的参数作为一个数组传入
function buildName(firstName: string, ...restOfName: string[]) {
    return firstName + " " + restOfName.join(" ");
}
let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");

4.3 interface (interface)

An interface is a declaration of a series of abstract methods. It is a collection of method features. These methods should be abstract and need to be implemented by specific classes. Then third parties can use this group of abstract method calls to let specific classes execute specific methods. Methods.

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

Interfaces can extend themselves through inheritance. Inheritance uses the keyword extends, which can be single-inherited or multiple-inherited.

interface Person { 
   age:number 
} 
interface Musician extends Person, person1 { 
   instrument:string 
}

4.4 Classes

TypeScript is object-oriented JavaScript, and classes describe the common properties and methods of created objects.
The keyword to define a class is class, followed by the class name. A class can contain the following modules (data members of a class):

  • Fields − Fields are variables declared inside a class. Fields represent data about an object.
  • Constructor − Called when a class is instantiated and can allocate memory for objects of the class.
  • Method − A method is an action to be performed by an object.
class Car { 
    // 字段 
    engine:string; 
    // 构造函数 
    constructor(engine:string) { 
        this.engine = engine 
    }  
    // 方法 
    disp():void { 
        console.log("发动机为 :   "+this.engine) 
    } 
}
const car = new Car('')

5 summary

Overall, TypeScript is a great tool to include in your study plan even if you haven't used it before. Because it can sow the seeds of "type thinking" in your mind, and the way of thinking determines programming habits, programming habits lay the foundation for engineering quality, and engineering quality defines the boundaries of capabilities. In the face of increasingly complex front-end scenarios, the way of thinking provided by TypeScript can benefit you for a long time in future development.

Author: JD Logistics Wu Yunkuo

Source: JD Cloud Developer Community

{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/4090830/blog/10085442