Install Typescript

1. The NPM/CNPM installation
// Typescript installation
npm install -g typescript

// Typescript verifies that the installation was successful
tsc -v
// If the installation is successful, the Version number, for example, Version 4.3.5, is displayed
Copy the code
2. The yarn is installed
/ / installation of yarn
npm install -g yarn

// Typescript installation
yarn global add typescript

// Typescript verifies that the installation was successful
tsc -v
// If the installation is successful, the Version number, for example, Version 4.3.5, is displayed
Copy the code

Implement a simple ‘Hello TS’

1. Directory structure



2. Implement a simple ‘Hello TS’
// index.ts

console.log('hello ts')
// ts builds es5
var str:string = "Hello ts"
Copy the code
3. The manual input command that ts becomes JS
tsc index.ts  // An index.js file is automatically generated and updated after running the command several times
Copy the code
4.
t s become j s Hot update configuration for \color{red}{ts to JS hot update configuration}
  • In a blank folder type TSC –init (this will automatically generate a tsconfig.json file)
  • In tsconfig.json, change outDir to outDir: ‘./js’
  • Create the index.ts file
let str:string = "Hello TS"
let str1:string = "Hello?"
Copy the code
  • Click Terminal — Run task — typescript — TSC: monitor — tscconfig.json
  • The directory structure of index.js is automatically generated



  • Every time a change to index.ts is saved, it is automatically updated to index.js

An introduction to Typescript types

1. Boolean (Boolean) true false
var flag:boolean = true
flag = false
Copy the code
2. Number type
var a:number = 123
console.log(a)
var b:number = 456.88 // ts number includes floating point types
console.log(b)
Copy the code



3. String type (string)
let str:string = "Hello TS"
console.log(str)
Copy the code
4. Array types
// The first way to define an array
let arr1:number[] = [1.2.3.4] // In ts, whether we use var or let, we convert js to var
let arr2:string[] = ["1"."2"."3"."4"] // The string can be quoted in single or double quotes. Double quotes are recommended

// The second way to define an array
let arr3:Array<number> = [11.22.33.44]
let arr4:Array<string> = ["11"."22"."33"."44"]
Copy the code
5. A tuple is a type of array
// The first way
let arr1:[string,number,boolean] = ['12'.34.false]

// The second method is any
let arr2:any[] = ['111',number,false]
Copy the code
6. Enumeration Type (enum)
// Flag 1: true -1: false
 enum Flag  {success=1, error=-1} // If there is no assignment, the index value will be printed during printing. If the previous one has an assignment and the latter one has no assignment, then the index value of the latter one is the previous one +1
 var f:Flag = Flag.success
 console.log(f)
 // Prints 1
Copy the code
7. Any type
var nums:any = 123 // Can be written as any type
// Any type of use
var oBox = document.getElement('box') // An error will be reported
var oBox:any = document.getElement('box') // Add any type to ts to avoid errors
oBox.style.color = 'red'
Copy the code
Null and undefined subtypes of other (never) data types
var other1:undefined;
var other2:number | undefined; // Can be used and can be assigned to number or not
var other3:null;
// An element can be number, null, or undefined
var other4 : number | null | undefined ;
Copy the code
Void void void void void void void void void void void void void
function run () :void {
   console.log('run') 
}
run()
Copy the code
10. The never type: is a subtype of other types (including null and undefined) and represents a value that never occurs
// This means that variables declaring never can only be assigned by type never
var never1:undefined;
never1 = undefined

var never2:null;
never2 = null

var a:never;
a(() = >{
   throw new Error('wrong')
})()
Copy the code

Functions in Typescript

1.TypescriptDefine a functionIn two ways
// Function declaration
function run() :string {   // string indicates that the return value type is string
  return 'run'
}
run()

// The second kind of function expression
var run2 = function () :number {  // number Indicates that the return value type is number
  return 123
}
run2()

Copy the code
2.TypescriptDefine the parameterIn two ways
// Function declaration
function getinfo(name: string, age: number) :string {
  return `${name} --- ${age}`
}
getinfo('Typescript'.20)

// The second kind of function expression
var getinfo2 = function (name: string, age: number) :string {
  return `${name} --- ${age}`
}
getinfo2('Typescript'.200)
Copy the code
3.TypescriptNo return valueThe method of
function norun() :void {
  console.log('run')
}
norun()
Copy the code
4. The Typescript methodOptional parameters
  • The arguments and parameters of ES5 methods can be different, but they must be the same in TS. If they are different, you need to configure optional parameters
  • Note: Optional parameters must be configured at the end of the parameter
function getinfo(name: string, age? : number) :string {  / /? Age indicates that age is optional
  if (age) {
    return `${name} --- ${age}`
  } else {
    return `${name}-- Age is confidential
  }
}
alert(getinfo('Typescript'))
Copy the code
5. The Typescript methodThe default parameters
  • You cannot set default parameters in ES5. You can set default parameters in ES6 and TS
function getinfo(name: string, age: number = 20) :string {
  return `${name} --- ${age}`

}
alert(getinfo('Typescript'))    // The default value is 20
alert(getinfo('Typescript'.30)) // If the value is passed, the value is 30
Copy the code
6. The Typescript methodThe remaining parameters
// The sum is written in general
function sum(a: number, b: number, c: number, d: number) :number {
  return a + b + c + d
}
alert(sum(1.2.3.4))

// The three-point operator receives the value of the new parameter
// The first way is:
function sum(. result: number[]) :number {
  var sum = 0;
  for (var i = 0; i < result.length; i++) {
    sum += result[i]
  }
  return sum
}
alert(sum(1.2.3.4.5.6))

// The second way:
function sum(a:number,... result: number[]) :number { // Assign a to sum and the rest to result. The result is the same
  var sum = a;
  for (var i = 0; i < result.length; i++) {
    sum += result[i]
  }
  return sum
}
alert(sum(1.2.3.4.5.6))
Copy the code
7. The Typescript methodFunction overloading
  • Method overloading in Java: Overloading is when two or more functions of the same name have different arguments
  • Overloading in TS: The purpose of multiple functions by providing definitions of more than one function type for the same function
  • Ts overloads are written differently from Java for ES5 and ES6 compatibility
// A method with the same name appears in ES5. The following method replaces the above method
function fun(config: any) :any {}
function fun(config: any, value: any) :any {}

// Overloading in ts: arguments are different
function getinfo(name: string) :string;
function getinfo(age: number) :number;
function getinfo(str: any) :any {
  if (typeof str === 'string') {
    return 'my name is: + str
  } else {
    return 'My age is:' + str
  }
}
alert(getinfo('Joe'))
alert(getinfo(20))

// overloading in ts: same arguments
function getinfo(name: string) :string;
function getinfo(name: string,age: number) :string;
function getinfo(name: any,age? : any) :any {
  if(age) {
    return 'My name is:'+name +The '-'+ 'My age:'+age
  }else {
    return 'My name is:'+name
  }
}
alert(getinfo('Joe'))
alert(getinfo('TS overloading'.20))
Copy the code
8. The Typescript methodArrow function
  • The this in the arrow function points to the context
var fun = ((a:string,b:number):string= > {
  return a + b
})
alert(fun('Arrow function'.6))
Copy the code

Classes in Typescript

1. ReviewES5Internal inheritance
// The function to be inherited
function Person(name, age) {
   this.name = name;
   this.age = age;
}
Person.prototype.work = function () {
   console.log('I love to work!! ')}// The inherited function
function Fun(name, age, sex) {
   Person.call(this, name, age)   // Object impersonates inheritance
   this.sex = sex
}
Fun.prototype = new Person()    // Prototype chain inheritance
Fun.prototype.constructor = Fun   // Make it point to yourself
Fun.prototype.study = function () {
   console.log('I love learning!! ')}let tljx = new Fun(Fried Snow with Crabapple pear.18.'woman')
console.log(tljx)
tljx.work()
tljx.study()
Copy the code
2. ReviewES6Internal inheritance
class Person {
   constructor(name, age) {
      this.name = name
      this.age = age
    }
   work() {
     console.log('I love to work!! ')}}class Fun extends Person {
    constructor(name, age, sex) {
      super(name, age)
      this.sex = sex
    }
    study() {
      console.log('I love learning!! ')}}let tljx = new Fun(Fried Snow with Crabapple pear.18.'woman')
console.log(tljx)
tljx.work()
tljx.study()
Copy the code
3. In the Typescriptclass
class Person {
  name:string // The public keyword is omitted before the attribute
  constructor(name:string) { // the method fired when the constructor instantiates the class
    this.name = name;
  }
  run():void {
    alert(this.name)
  }
}
var p = new Person(Fried Snow with Crabapple pear)
p.run()
Copy the code
class Person {
  name:string // The public keyword is omitted before the attribute
  constructor(name:string) { // the method fired when the constructor instantiates the class
    this.name = name;
  }
  getName():string {
    return this.name
  }
  setName(name:string):void {
    this.name = name
  }
}
var p = new Person(Fried Snow with Crabapple pear)
alert(p.getName())
p.setName('Typescript')
alert(p.getName())
Copy the code
4. The Typescriptinheritance
class Person {
  name: string
  age: number
  constructor(name: string, age: number) {
    this.name = name
    this.age = age
  }
  work(): void {
    console.log('I love to work!! ')}}class Fun extends Person {
  sex: string
  constructor(name: string, age: number, sex: string) {
    super(name, age)
    this.sex = sex
  }
  study(): void {
    console.log('I love learning!! ')}}let tljx = new Fun(Fried Snow with Crabapple pear.18.'woman')
console.log(tljx)
tljx.work()
tljx.study()
Copy the code
5. The TypescriptInheritance to investigate
  • The methods of the parent class and the methods of the child class are the same, so do you use the parent class or the child class?
class Person {
  name: string
  age: number
  constructor(name: string, age: number) {
    this.name = name
    this.age = age
  }
  work(): void {
    console.log('I love to work!! ')}}class Fun extends Person {
  sex: string
  constructor(name: string, age: number, sex: string) {
    super(name, age)
    this.sex = sex
  }
  work(): void {
    console.log('I love learning!! ')}}let tljx = new Fun(Fried Snow with Crabapple pear.18.'woman')
console.log(tljx)
tljx.work() // I love learning!!
Copy the code
6.TypescriptClass modifier
  • Typescript provides us with three modifiers when defining properties
  • Public: public, accessible inside, subclasses, and outside classes
  • Protected: Protected type, accessible within a class, within a subclass, but not outside the class
  • Private: private, accessible from within a class, but not from a subclass or outside the class
  • Property without modifier, default is public
7.Typescript class static methods
  • Simply add static before the instance method
class Person {
  name: string
  age: number
  static sex="Female" // Static method
  constructor(name: string, age: number) {
    this.name = name
    this.age = age
  }
  static work(): void { // Work is a static method where class properties cannot be called directly
    console.log('I love to work!! ')
    console.log('I love to work!! ' + Person.sex)
  }
}
let tljx = new Person(Fried Snow with Crabapple pear.18)
console.log(tljx)
tljx.work() // I love learning!!
Copy the code
8. The Typescriptpolymorphismmethods
  • A parent class defines a method that is not implemented and lets its subclasses implement it, each of which behaves differently
  • Polymorphism is inheritance
9. The Typescriptabstractmethods
  • Abstract classes in Typescript are base classes that provide inheritance from other classes and cannot be instantiated directly
  • The abstract keyword is used to define an abstract class and an abstract method. Abstract methods in an abstract class contain no concrete implementation and must be implemented in a derived class
  • Abstract methods can only be placed in abstract classes
  • Abstract classes and abstract methods are used to define standards
  • Abstract classes cannot be instantiated
abstract class Person {
  name: string
  age: number
  constructor(name: string, age: number) {
    this.name = name
    this.age = age
  }
  abstract eat(): any;
}
// var a = new Person() // The abstract class cannot be instantiated
class Dog extends Person {
  // Subclasses of the abstract class must implement the abstract methods in the abstract class
  constructor(name: string, age: number){
    super(name,age)
  }
  eat(): any {
     console.log(this.name + Love to eat)}}var dog = new Dog('wangwang'.12)
dog.eat()
Copy the code

Interfaces in Typescript

1.Attribute classinterface
  • Constraints on JSON
interface nameJson {
  firstName: string;  / / note; The end of the
  secondName: string
}
function printName(name: nameJson) :void {
  console.log(name.firstName + '-- -- -- -- -- -- -- + name.secondName)
}

// The first way
printName({
  // obj:20, write and define nameJson is not a corresponding error
  firstName: 'tangli'.secondName: 'Fried snow'
})

// The second way
var obj = {
  obj: 20.// You can write key and value values that are not in nameJson
  firstName: 'tangli'.secondName: 'Fried snow'
}
printName(obj)
Copy the code
2.Optional attributeinterface
interface nameJson {
  firstName: string; secondName? : string// Optional attributes of the interface
}
function printName(name: nameJson){
  console.log(name)
}
printName({
  firstName: 'tangli'.// secondName: 'Saute snow
})
Copy the code
3. Attribute interfacesNative AJAX encapsulation
interface Config {
  type: string; url: string; data? : string; dataType: string }function ajax(config: Config) {
  var xhr = new XMLHttpRequest();
  xhr.open(config.type, config.url, true)
  xhr.send(config.data)
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      console.log("Success")
      if (config.dataType === 'json') {
        JSON.parse(xhr.responseText)
      } else {
        console.log(xhr.responseText)
      }
    }
  }
}

ajax({
  type: 'get'.url: 'https://www.baidu.com/'.// Simulate a false interface
  data: '111'.dataType: 'json'
})
Copy the code
4.Function typesinterface
  • Constrain the parameters passed to the method, as well as the return values
  • Encrypted function type interface
interface encrypt {
  (key:string,value:string):string
}

var md5:encrypt = function(key:string,value:string) :string{
  // simulate the operation
  return key+value;
}
console.log(md5('name'.Fried Snow with Crabapple pear))
Copy the code
5.But the indexInterface (array, object constraints, not often used)
  • Constraints on arrays
interface Arr {
  [index: number]: string // index The index value is number and value is string
}
// Constraints on arrays
var arr: Arr = [Fried Snow with Crabapple pear.'1234']
console.log(arr[1])
Copy the code
  • Constraints on objects
interface Obj {
  [index:string]:string
}
// Constraints on objects
var obj:Obj={name:Fried Snow with Crabapple pear.age:'18'}
console.log(obj)
Copy the code
6.Class typesInterfaces (constraints on classes, similar to abstract classes)
interface Animal {
  name: string;
  eat(str: string): void
}
class Dog implements Animal { // implements the interface
  name: string;
  constructor(name: string) {
    this.name = name
  }
  eat() {
    console.log(this.name + 'Have a meal')}}var p = new Dog('wang wang')
p.eat()
Copy the code
7. Interface extension (interface can inherit interface)
interface Animal{
  eat():void;
}
// Inherit the Animal interface
interface Dog extends Animal {
  work():void
}
// implements is the keyword for implementing the interface
class Cat implements Dog {  // Implement the Dog interface
    public name:string;
    constructor(name:string){
       this.name = name
    }
    eat () {
      console.log(this.name + 'Have a meal')
    }
    work () {
      console.log(this.name + 'Love work')}}var p = new Cat('white')
p.eat()
p.work()
Copy the code
  • You can inherit classes and implement interfaces
/ / such as
class Cat extends Parent implements Dog {} 
// Cat is the defined class
/ / Parent: the Parent class
/ / Dog: interface
Copy the code

Generics in Typescript

1. Understanding generics
  • Generics address the reuse of classes, interface methods, and support for non-specific data types
2. Types of generics
  • Only string data can be returned
function getDate(value:string) :string {
  return value;
}
Copy the code
  • Both string and number are returned
Any can be implemented, but any abandons type checking, but what do we want passed in and returned
function getDate(value:any) :any {
  return value;
}

// Generic, which can support non-specific data types
// Requirements: The parameters passed in are the same as those returned
// T stands for generics. What type is determined when this method is called
function getData<T> (value:T) :T {
  return value
}
console.log(getData<number>(123)) // Define number, which must be passed in
Copy the code
  • Generic classes: For example, there is a minimal heap algorithm that needs to support returning both numbers and strings
// Only minimum heap algorithms that support numeric types are returned
class minNumber {
  public list: number[] = [];
  add(num: number) {
    this.list.push(num)
  }
  min():number {
    var minNum = this.list[0]
    for (var i = 0; i < this.list.length; i++) {
      if (minNum > this.list[i]) {
        minNum = this.list[i]
      }
    }
    returnminNum; }}var p = new minNumber()
p.add(2)
p.add(123)
p.add(1)
alert(p.min())
Copy the code
// Generic classes: minimum heap algorithms that return both numbers and strings
class minNumber<T> {
  public list: T[] = [];
  add(num: T): void {
    this.list.push(num)
  }
  min(): T {
    var minNum = this.list[0]
    for (var i = 0; i < this.list.length; i++) {
      if (minNum > this.list[i]) {
        minNum = this.list[i]
      }
    }
    returnminNum; }}var p1 = new minNumber<number>() // Instantiate the class and specify that T of the class represents type number
p1.add(2)
p1.add(123)
p1.add(1111)
alert(p1.min())

var p2 = new minNumber<string>() // Instantiate the class and specify that T of the class represents type string
p2.add('2')
p2.add('123')
p2.add('1111')
alert(p2.min())
Copy the code
Generic interfaces
  • Interface of a function
interface Config {
  (value1:string,value2:string):string
}

var setData:Config = function(value1:string,value2:string) :string {
  return value1+value2
}
console.log(setData('tangli'.'Fried snow'))
Copy the code
  • Generic interface
// The first way to define generic interfaces
interface Config {
  <T>(value: T): T
}
var setData: Config = function <T> (value: T) :T {
  return value
}
console.log(setData(Fried Snow with Crabapple pear))
Copy the code
// The second way to define generic interfaces
interface Config<T> {
  (value: T): T
}
function setData<T> (value: T) :T {
  return value
}
var mysetData:Config<string> = setData
console.log(mysetData(Fried Snow with Crabapple pear))
Copy the code
4. Generic classes: Generic classes that take classes as arguments (constraints)
// Define a User class that maps database fields
// Then define a MysqlDb class to operate on the database
// Pass the User class as an argument to MysqlDb

class User {
  username: string | undefined;
  password: string | undefined
}
class MysqlDb {
  add(user: User): boolean {
    console.log(user)
    return true}}var u = new User()
u.username = "Fried Snow with Crabapple pear"
u.password = "123"
var s = new MysqlDb()
s.add(u)
Copy the code
// Use generics

class User{
  username: string | undefined;
  password: string | undefined;
  constructor(params:{
    username: string | undefined;
    password: string | undefined;
  }){
    this.username = params.username
    this.password = params.password
  }
}
var u = new User({
  username:Fried Snow with Crabapple pear.password:'123456'
})
class MysqlDb<T> {
  add(user: T): boolean {
    console.log(user)
    return true}}var s = new MysqlDb<User>()
s.add(u)
Copy the code

A comprehensive application of Typescript types, interfaces, classes, and generics

Mysql Mssql MongoDb Mysql Mssql MongoDb add update delete get Mysql Mssql MongoDb add update delete get

// Generic interface
interface User<T> {
  add(info: T): boolean;
  update(info: T, id: number): boolean;
  delete(id: number): boolean;
  get(id: number): any[]; // Get an array of any type
}

// define a library to operate on the database Mysql
// Note: To implement a generic interface, this class should also be a generic class
class MysqlDb<T> implements User<T>{
  add(info: T): boolean {
    console.log(info)
    return true
    // throw new Error("Method not implemented.");
  }
  update(info: T, id: number): boolean {
    throw new Error("Method not implemented.");
  }
  delete(id: number): boolean {
    throw new Error("Method not implemented.");
  }
  get(id: number): any[] {
    throw new Error("Method not implemented."); }}// Define a library Mssql that operates on the database
// Note: To implement a generic interface, this class should also be a generic class
class MssqlDb<T> implements User<T>{
  add(info: T): boolean {
    throw new Error("Method not implemented.");
  }
  update(info: T, id: number): boolean {
    throw new Error("Method not implemented.");
  }
  delete(id: number): boolean {
    throw new Error("Method not implemented.");
  }
  get(id: number): any[] {
    throw new Error("Method not implemented."); }}// define a library to operate the database MongoDb
// Note: To implement a generic interface, this class should also be a generic class
class MongoDbDb<T> implements User<T>{
  add(info: T): boolean {
    throw new Error("Method not implemented.");
  }
  update(info: T, id: number): boolean {
    throw new Error("Method not implemented.");
  }
  delete(id: number): boolean {
    throw new Error("Method not implemented.");
  }
  get(id: number): any[] {
    throw new Error("Method not implemented."); }}class UserDb{
  username:string | undefined;
  password:string | undefined
}

var u = new UserDb()
u.username = "Fried Snow with Crabapple pear"
u.password="666666"

var oMysql = new MysqlDb<UserDb>() Class as a parameter to constrain the type of data passed in
oMysql.add(u)
Copy the code