First, learn TypeScript

TypeScript is a superset of JavaScript that provides the type system and SUPPORT for ES6. TypeScript is developed by Microsoft with code originated on GitHub.

Its first release was in October 2012, and after several updates, it has now become a force to be reckoned with in the front end community, widely used not only within Microsoft, Google-developed Angular has been developing with TypeScript since 2.0, and Vue 3.0 has been refactoring with TypeScript.

TypeScript is a free and open source programming language developed by Microsoft. It is a superset of JavaScript and essentially adds optional static typing and class-based object-oriented programming to the language.

TypeScript offers the latest and evolving JavaScript features, including those from ECMAScript 2015 and future proposals, such as asynchronous functionality and Decorators, to help build robust components.

What is the TypeScript

  • TypeScript is a free and open source programming language developed by Microsoft. TypeScript is a superset of JavaScript, extending the syntax of JavaScript, providing a type system and support for ES6.
  • TypeScript is designed for large-scale applications that can be compiled into pure JavaScript that can run on any browser.

How JavaScript differs from TypeScript

  • TypeScript is a superset of JavaScript, extending JavaScript’s syntax so that existing JavaScript code can work with TypeScript without modification. TypeScript provides static type-checking at compile time through type annotations.
  • TypeScript handles existing JavaScript code and compiles only TypeScript code within it.

The advantage of the TypeScript

  • Angular2, VuE3 development language

  • Code readability and maintainability: for example, 🌰 to see the return value of an interface on the back end, you usually need to go to network to see or to see the interface document to know the returned data structure, but after using ts correctly, the editor will remind the interface of the type of return value, which is quite useful.

    Most of the errors were found during compilation, and many online bugs were avoided

    Editor and IDE enhancements, including code completion, interface prompts, jump to definition, refactoring, and more

The disadvantage of TypeScript

  • There is a certainLearning costsYou need to understand Interfaces, Generics, Classes, Enums, and other concepts that front-end engineers may not be familiar with
  • It will increase a little bitDevelopment costsOf course, this is early, later maintenance is simpler
  • Some JavaScript libraries doCompatible withFor example, vuE2, the underlying compatibility with TS is not very good.
  • Ts compilation is requiredtimeThis means that as the project gets bigger, the speed at which the development environment is launched and the production environment is packaged becomes a test

Two, environment construction

Install the TS compiler globally:

NPM install typescript -g TSC -h // View all commands TSC -v // View the version numberCopy the code

TSC [options] [file…]

TSC hello.ts // compiles the.ts file of the directive to a.js file. tsc ./src/app.ts --outFile ./dist/app.jsCopy the code

Automatically listens for ts file changes and compiles to JS

tsc --rootDir ./src/* --outDir ./dist --watch
Copy the code

Generate ts project configuration file tsconfig.json:

tsc --init
Copy the code

/ SRC “and “outDir”: “./dist”. Run again:

tsc --watch
Copy the code

Three or five minutes to get started with TypeScript

1. Type annotations

Type annotations in TypeScript are a lightweight way to add constraints to functions or variables.

let name:string = 'Jane'
Copy the code
Function greet(person:string) {return 'hello ', '+person } greet('Jane') greet(name) // Argument of type 'number' is not assignable to parameter of type 'string'. greet(20) // Expected 1 arguments, but got 0. greet()Copy the code

When you have errors in your.ts code, you can still use TypeScript and still compile smoothly to.js files. But in this case, TypeScript warns you that your code might not perform as expected.

2, interfaces,

In TypeScript, only structures that are compatible within two types are compatible. This allows us to implement the interface without explicitly using the implements statement as long as we are sure to include the structure required by the interface.

Person {firstName: string, lastName: string; String} function greet(p:Person) {return 'hello' ${p.filstname} ${p.lastname} '} firstName:'zhang', lastName:'san' } greet(user)Copy the code
3, class,

TypeScript supports new features of JavaScript, such as support for class-based object-oriented programming. Let’s create a Student class with a constructor and some public fields. Note that classes and interfaces can work together.

// class Student {public fullName = "constructor" public fullName = "constructor"; Public lastName) {this.fullname = '${firstName} ${lastName}'}} interface Person {firstName: string, lastName: Function greet(p:Person) {return 'hello ${p.filstname} ${p.lastname}' Student('zhang', 'san') greet(user)Copy the code

Basic data types

TypeScript supports almost the same data types as JavaScript, plus useful tuples, enumerations, any, and void.

1. Boolean, number, string
// Let isBol: Boolean = false // Let age: number = 20 string = 'zhangsan' myname = "li si" let msg = `${myname}'s age is ${age}`Copy the code
2. Arrays and tuples
Let arR1: number[] = [1,2,3] Let arR2: string[] = ['1','2','3'] Array<number> = [4,5,6] let arr4: Array<string[]> = [['1','2'],['3','4']] // Tuple // Tuple type allows to represent an Array with known number and type of elements. An error occurs when accessing an out-of-bounds tuple element. Let x: [string, number, Boolean] = [' hello ', 30, true]. The console log (x x [0], [1], [2]) x/x [3] = 'world' / / an errorCopy the code
3. Enumeration types
// enumenum Cate {office = 'office ', clothe =' clothe ', sport = 'Outdoor ', } let office_zh1 = Cate. Office console.log('enum', Cate)Copy the code
4. The type is any or void
NoSure = 'hello any' noSure = [1,2,3] // let noSureArr: Array<any> = ['hello', false, 23] let noSureArr: any[] = ['hello', false, 23] // void type. // Declaring a void variable is not useful, because you can only give it undefined and null let v1: void = undefined let v2: Void = null // When a function does not return a value, you usually see a return value of type void function foo(arg:any): void {console.log(' this function returns a value of type void')}Copy the code

Five, the function

1. Function declaration
Function sum(x: number, y: number): Number {return x + y} sum(1,2) {return x + y} sum(1,2)Copy the code
2. Function expression
let sub = function(x: number, y: number): Interface SearchFunc {(source: string, subStr: string): SearchFunc {(source: string, subStr: string); boolean } let search: SearchFunc = function(source: string, subStr: string) { return source.search(subStr) ! = = 1}Copy the code
3. This parameter is optional
/ / to use? Indicates an optional parameter. The optional parameter must be followed by the required parameter. No required parameter is allowed after the optional parameter. function foo(a: string, b? :string): string { if(b) return a+b return a } foo('hello') foo('hello','world')Copy the code
4. Default parameters
// TypeScript recognizes arguments with default values as optional. Function bar(a:string='hello', b:string) {return a +b} bar(undefined,'world') bar('hi', 'lisi')Copy the code
5. Remaining parameters
// The rest of the function arguments can be used... Function push(arr:any[],... Rest: any []) : any [] {return} [... arr... rest] push ([0], 1, 2, 3, 4)Copy the code
6. Function overload
function reverse(x: number): number function reverse(x: string): string function reverse(x: number | string): number | string { if (typeof x === 'number') { return Number(x.toString().split('').reverse().join('')) } else if (typeof x === 'string') {return x.plit (" ").reverse().join(" ")}} // TypeScript matches the first function definition first, so if multiple function definitions have containment relationships, the exact definition needs to be written first. reverse(100) reverse('hello')Copy the code

Six, interfaces,

What is an interface? Interfaces are an important concept in object-oriented languages. They are abstractions of behavior that need to be implemented by classes. Interfaces in TypeScript are a very flexible concept. In addition to abstracting part of the behavior of a class, they are often used to describe the Shape of an object.

In TypeScript, we use Interfaces to define object types, as shown in the following example:

Interface Person {name: string, age: number, age: number, mobile? : string, // optional attribute [propName: string]: any, // Optional attribute readonly role: number, // read-only attribute} // When assigning a value, the shape of the variable must be consistent with the shape of the interface. Person = { name: 'tom', age: 30, mobile: '110', gender: 'male', role: 1 }Copy the code
  • Note 1: [propName: string] defines any property to take a value of type string. Once an arbitrary attribute is defined, the type of both the deterministic attribute and the optional attribute must be a subset of its type.
  • Note 2: The read-only constraint exists the first time an object is assigned a value, not the first time a read-only attribute is assigned.

Seven, generics

Generics is a feature that defines a function, interface, or class without specifying a specific type in advance, but instead specifies the type when it is used.

Function print<T>(arg: T): void {console.log('arg', 'arg')} print<string>('hello') print<number>(100) print<any>(1.2345)Copy the code
function add<T>(x: T, y: T, z: T): Void {the console. The log (x, y, z)} the add < number > (1, 2, 3) add < string > (' a ', 'b', 'c') add < any > (' a ', 20, 'c')Copy the code

Support for multiple generics

function swap<T,U>(tup:[T,U]): [U,T] {
    return [tup[1], tup[0]]
}
swap<number, string>([100, 'hello'])   // ['hello', 100]
interface MyU { a: string; b: number }
swap<boolean, MyU>([true, {a:'hi',b:11}])  // [{a:'hi',b:11}, true]
Copy the code

2. Generic constraints

Interface LengthType {length: number} function printLength<T extends LengthType>(arg: T): number { Because the data type of the input parameter is uncertain, } printLength<string>('hello') // 5 printLength<Array<any>>([1,2,'a','b']) // 4Copy the code

3. Generic classes

class Dog<T> { name: T constructor(name: T) { this.name = name } sayHi(): T {return this.name}} const dog = new dog <string>('dahuang') // Call constructor() dog.sayhi ()Copy the code

4. Generic interfaces (generic types)

interface Tfn1<T> { (x: T, y: T, z: T): T } const tf1: Tfn1<number> = function(x: number, y: number, z: number): Number {return x * y * z} tf1(1,2,3) const tf3: Tfn1<string> = function(x: string, y: string, z: string): string { return x + y + z } tf3('a','b','c')Copy the code
interface Tfn2 {
    <T>(x: T, y: T, z: T): void
}
const tf2: Tfn2 = <T>(x:T, y:T, z: T): void => {
    console.log(x, y, z)
}
// const tf2: Tfn2 = function <T>(x:T, y:T, z: T):void {
//  console.log(x, y, z)
// }
tf2<string>('a','b','c')
tf2<number>(10, 20, 30)
Copy the code