preface

TS is a superset of javaScript, according to TS website. The so-called superset means that JS has something, I TS has, JS does not, I TS has, that in the end TS provides us what additional things? Let’s look at the simple description of js this language, and then everything will be clear.

Js language features

JavaScript is a dynamically weakly typed language.

Those of you familiar with JS know that weak typing occurs when you declare a variable, such as a string, but then you can assign it to other types of data.

// let a = 'string'; // Let a = 'string'Copy the code

In contrast, strongly typed languages are those in which the value type of a variable cannot be changed after being declared.

Dynamic means that only at the execution stage can the types of all variables be determined. As we know, JS is a scripting language, which does not need to be compiled in advance. When js code is run, the JS engine will execute while compiling.

// Since the input parameter is uncertain, this js function can only be executed when, Function add(x,y){return x + y} add(2,4) // return 6 return number add('a','b') // return 'ab' returns stringCopy the code

Statically typed languages then determine the types of all variables at compile time.

Js pain points

Talk about some of the problems I have with using JS in practice

  1. The type of a variable may not be clear in the later maintenance phase after a large project and increased code volume. It is common to call a method on a variable that results in a null value and an error.
  2. When the interface is combined, the back end will return an object with a deeper level and more attributes. When I use it to write business code, I can only know what is in it by looking at the interface document, which has an impact on efficiency.
  3. Interface returns data without type constraints, often with TypeError.

Functions provided by TS

  1. I think TS is turning JS into a statically strongly typed language. It provides type constraints that help us reframe type thinking and reduce code errors.
  2. With vscode’s code prompt function, you can improve the efficiency of development.

The use of TS

Since ts is written and executed, new NPM projects are required, as well as the packaging and compilation of build tools, but this is not covered here, just the basic usage of TS.

The base type

Js for those original data types, when using TS declaration, just add a colon after the variable and the type name can be.

// let name:string = 'typescript'; // let age: number = 18; // If age is assigned to another type, Age = '18' // Type 'string' is not assignable to Type 'number'. // Boolean let isFlag: Boolean = false // Null let Defiend :null = NULL // Undefiend type let isUnde:undefined = undefined // symbol type let ID :symbol = symbol (1) // Object type let Peolpe :object = {id name, age} let list:number[] = [1,2,3]Copy the code

In practice, ts null and undefined are not commonly used, because it does not make sense to declare a null or undefined variable. The declaration of this data type is only used in JS, for example, when the program is initialized, the first null variable is declared. Change to other data types in subsequent code logic.

In addition to these data types, TS also has new meta-ancestor and enumeration types.

Enumerated types are really useful because they can give a meaningful description of a value.

Some fields, for example, have multiple values, and each value has a different meaning, but if we use these values directly to distinguish and write the code logic, later maintenance will be more difficult, because you need to understand what these values mean before you write the code.

Js code

Let userType switch(userType){case 1: // Student user code logic case 2: // parent user code logic case 3: // Teacher user code logic}Copy the code

With this code, if you don’t have a comment, after a while you probably won’t know what the values mean, but using the enumeration of TS is fine.

Ts code rewrite

enum UserType { student = 1, parents = 2, teacher = 3 } let userType:UserType switch(userType){ case UserType.student: Parents: // parents: // teacher: // teacher: // teacher: // teacher: // teacher: //Copy the code

This is not at a glance, increase the readability of the code, the later maintenance is also easy.

interface

Interface is the front not seen before a concept, in the base type, we only constraints, the type of a variable, however, in the actual development, we will be organized into some of the structure of the data, and the role of the interface is the value of these structure type constraints, it is also known as canard type method, which means that if a thing, like a duck, If it quacks like a duck, it’s a duck.

Interfaces can constrain the structure of objects, functions, and classes.

Let’s take an example

Object interface

// Define a constraint object's interface, interface People {age:number; name:string; } let child:People = {age: 18, name: 'xiaoming'}Copy the code

This completes the type checking of the child through the interface, but the interface is very restrictive, so if you have one more attribute in the data structure, or one less attribute, TS will say something like this.

Let child:People = {age: 18, name: 'xiaoming', // add an undefined variable attribute to the interface tel: 177734234234}Copy the code

However, the interface can add an optional attribute

  interface People {
   age:number;
   name:string;
   // 不必须
   tel?: number;
 }
Copy the code

The tel variable is then optional and can be omitted when declared without type checking errors.

The function interface

Interface Add {// directly write function type (x:number,y:number):number} let Add :Add = (a,b) => a + bCopy the code

When actually writing a function, the parameter names in the function need not be the same as those defined in the interface. Ts will match the positions.

Index type interface

Indexable types have an index signature that describes the type of the object’s index and the corresponding index return value type. Let’s look at an example:

Ts supports only two index signatures: string and number

Interface NumList {// Number index, type constraint attribute name in parentheses, [index:number] :string} let array:NumList = ['a','b'] interface StringList {// Index :string] : string } let obj:StringList = {a:'a'}Copy the code

The generic

Generics are also a concept that the front end has never encountered. As mentioned above, we need to define the type of a variable when we declare it.

But sometimes, we might want to say that in practice, the variable can have different types, and that’s where generics come in.

Like function inputs, generics can be understood as arguments of variable types that are passed in for actual use.

Let’s say we define a function

  function createValue(val: number):number {
     return val + val
  }
Copy the code

We can use generics if we want this function to concatenate strings rather than just pass values

 function createValue<T>(val: T) : T{
    return val + val
   }
  
 createValue<string>('234')
 
 createValue<number>(234)
Copy the code

An Angle bracket is used as the input parameter position for the type, and the actual call passes in the specific data type. Of course, you don’t have to pass in data types like this, because the TS compiler makes type inferences based on the values that are passed in.

A few thoughts on TS

  1. I don’t think of it as a language at first, because it has a similar relationship to JS as sass and less have to CSS, and although it offers some extra features, it will eventually have to be compiled into JS because there is no JS engine that can run TS code directly.
  2. When I first started using it, I even felt it limited the flexibility of the original JS type, such as the various displays and invisible type conversions in JS, but it really hit me later. When we have a lot of code, maintenance costs increase, sometimes to determine the type of a function entry variable, but with TS there is no such problem.
  3. When we provide our functions to others, we can restrict the type of input arguments, reducing problems.

Ps: If there are any mistakes or supplements, welcome to comment and exchange