Primitive types: Number, String, Boolean, null, undefined, Symbol reference type: Array, Function, and Object TypeScript add the following data types to ES6 :void, any, Never, tuple, enumeration, and advanced

Type a,

1.1 Number type

let cml: number = 1
// es5: let cml = 1
Copy the code

1.2 type String

let cml: string = '1'
// es5: let cml = '1'
Copy the code

1.3 a Boolean type

let cml: boolean = true
// es5: let cml = true
Copy the code

1.4 Null type

let cml:null = null
// es5: let cml = null
Copy the code

1.5 Undefined type

let cml:undefined = undefined
// es5: let cml = undefined
Copy the code

1.6 Symbol type

const s2: symbol = Symbol(a);// TypeScript
const s1 = Symbol(a);// es5
console.log(s1 === s2) // false
Copy the code

1.7 Void type

Void can be assigned to undefined and null, but cannot be assigned to other types, such as string

let cml:void = undefined
// es5: let cml = undefined
cml = null
Copy the code

Summary:TypeScript does static type checking, and causes an error when a variable is assigned to a value of another type

but

  1. No error is reported when null and undefined are reassigned, because null and undefined can be considered subsets of all types

2. Null and undefined can only be assigned to itself

1.8 object

// let CML: Object = {x: 1, y: 1
let cml: {x: number.y: number} = {x: 1.y: 1}
cml.x = 2
console.log(cml)
Copy the code

1.9 an array

1 type + square brackets

let cml: number[] = [1.2.3]
// es5: let web = [1, 2, 3]
let web: any[] = [1.'2'.true]

Copy the code

2 the generic

let cml: Array<number> = [1.2.3]
// es5: let cml = [1, 2, 3]
Copy the code

3 interface

Class array: Built-in objects: IArgumenTypeScript, NodeList, HTMLCollection

function web(name: string, age: number) {
  let args: IArgumenTypeScript = argumenTypeScript;
  console.log(args);  // { '0': 'web', '1': 1 }
}
web('web'.1)
Copy the code

1.10 yuan group

A tuple is a special array that limits the type and number of arrays

let cml: [string.number] = ['666'.Awesome!]
console.log(cml) // ['666', 666]
Copy the code

Using subscripts, you can assign to only one of the items, but assign to the whole object must be complete, of the correct type, and with no more or less number

let cml: [string.number] = ['666'.Awesome!]
cml[0] = '888'
console.log(cml) / / [' 888 ', 666]
cml[1] = 888
console.log(cml) / / [' 888 ', 888]
cml = ['888'.888]
console.log(cml) / / [' 888 ', 888]
cml = ['888'.888.'888'] / / an error
Copy the code

Tuple out of bounds: More elements can be pushed, pushed, but still inaccessible

let cml: [string.number] = ['666'.Awesome!]
cml.push('888')
console.log(cml) / / [' 666 ', 666, '888')
console.log(cml[2]) / / an error
Copy the code

1.11 any type

The any type can be assigned arbitrarily, without the equivalent of any

let cml:any = '123'
cml = 123
Copy the code

1.12 never type

The never type represents the types of values that never exist. For example, the never type is a function expression that always throws an exception or returns no value at all.

// The function that throws an exception
let error: never = () = > {
  throw new Error('error')}// infinite loop function
let endLess: never = () = > {
  while(true) {}}Copy the code

1.13 Association Type

let cml:string | number
cml = '123'
cml = 123
Copy the code

Type assertions are for union types, and you can specify a type for a variable through assertions

function cml(a: number | string) :void {
  console.log(a.length) / / an error
  console.log((<string>a).length) // OK
}
Copy the code

In addition to the specified string/number types, TypeScript also supports custom types

type Cml = '666' | '888'
function cmlFun(a: Cml) :void {
  console.log(a)
}
cmlFun('666') // OK
cmlFun(Awesome!) / / an error
Copy the code

1.14 enum Enum type

1. Basic usage

enum Gender {Male, Female}
console.log(Gender) // {'0': 'Male', '1': 'Female', 'Male': 0, 'Female', 1}
console.log(Gender['0']) // Male
console.log(Gender['1']) // FeMale
console.log(Gender['Male']) / / 0
console.log(Gender['Female']) / / 1
Copy the code

ES5

// typescript
enum Gender {Male, Female}

// ES5
var Gender;
(function (Gender) {
    Gender[Gender["Male"] = 0] = "Male";
    Gender[Gender["Female"] = 1] = "Female";
})(Gender || (Gender = {}));
Copy the code

2. Enumeration of numbers

enum Direction {
  NORTH, / / the default 0
  SOUTH, / / 1 by default
  EAST, / / 2 by default
  WEST, / / 3 by default
}
let dir: Direction = Direction.EAST;
console.log('dir', dir) / / 2
Copy the code

The default is 0,1,2,3… If you define a number, the subsequent enumeration adds 1 to the previous enumeration value

enum Direction1 {
  NORTH = -1,
  SOUTH, / / to zero
  EAST = 4,
  WEST, / / 5
}
Copy the code

Note that self-appending enumeration values are not guaranteed to overlap with already set values

enum Direction1 {
  NORTH = 1,
  SOUTH = 0,
  EAST,
  WEST,
}
console.log(Direction1)
Copy the code

You can also change numbers to decimals

enum Direction1 {
  NORTH = 1.5,
  SOUTH, / / 2.5
  EAST, / / 3.5
  WEST, / / 4.5
}
console.log(Direction1)
Copy the code

3. Enumeration of strings

enum Direction1 {
  NORTH = 'a',
  SOUTH = 'b', 
  EAST = 'c', 
  WEST = 'd',}console.log(Direction1)  // { NORTH: 'a', SOUTH: 'b', EAST: 'c', WEST: 'd' }
console.log(Direction1['NORTH']) // a
console.log(Direction1['a'])  // undefined
Copy the code

4. Constant enumeration

Regular enumerations have objects. Constant enumerations have no objects. Object entities exist only in TypeScript and are removed when translated to ES5 code.

Purpose: When we do not need the object, only the value of the object, use constant enumeration, can reduce compile time code

/ / TypeScript code
const enum Gender {Male, Female}
let cml: Gender = Gender['Female']
console.log(cml)  / / 1

/ / ES5 code
var cml = 1 /* 'Female' */;
console.log(cml);
Copy the code

5. Heterogeneous enumeration

Heterogeneous enumerations have member values that are a mixture of numbers and strings:

enum Cml {
  A,
  B,
  C = "c",
  D = "d",
  E = 8,
  F,
}
Copy the code

Numeric enumerations differ from string enumerations in that numeric enumerations have more “reverse mapping” to string enumerations:

console.log(Cml[0]) // A
console.log(Cml['A']) / / 0
console.log(Cml['C']) // c
console.log(Cml['c']) // undefined
Copy the code

Second, the interface

1. Identify attributes

// Define an interface
interface IPerson {
  name: string.age: number
}

/ / instantiate
let p1: IPerson = {
  name: 'web'.age: 18
}
Copy the code

If a variable, such as p1 above, is declared as an instance of an interface, it must have no fewer or more attributes than those defined by the interface. Otherwise, an error will be reported.

2. Optional properties

interface IPerson {
  name: string, age? :number
}

/ / instantiate
let p1: IPerson = {
  name: 'web',}Copy the code

3. Arbitrary attributes

interface IPerson {
  name: string,
  [propName: string] :boolean | string
}

let p1: IPerson = {
  name: '123'.married: false.// ok
  country: '123' // ok
  age: 123 / / an error
}
Copy the code

If any attribute is set, all deterministic or optional attributes must be subsets of any attribute.

4. Read-only attribute

interface IPerson {
  readonly name: string.age: number
}

let p1: IPerson = {
  name: '123'.age: 18
}

let p2: IPerson = {
  name: '456'.// ok
  age: 18
}

p1.name = '456' / / an error
p1.age = 18
Copy the code

Readonly, which means that the value cannot be changed unless the object is assigned each time.

Three, functions,

1. Function definition

TypeScript defines functions in four ways:

  1. Declaration of functions
  2. Expression of a function
  3. Alias of a function
  4. Interface definition function

Declaration of functions

// function declaration in ES5
function cml(x, y) {
  return x + y
}
console.log(cml(1.2))  / / 3

// TypeScript function declarations
function cml(x: number, y: number) :number {
  return x + y
}
console.log(cml(1.2))  / / 3
Copy the code

Expression of a function

// ES5 function expression
let cml = function(x, y) {
  return x + y
}
console.log(cml(1.2))  / / 3

// TypeScript function expressions
let cml = function(x: number, y: number) :number {
  return x + y
}
console.log(cml(1.2))  / / 3
Copy the code

Alias of a function

type cmlFun = (x: number, y: number) = > x + y
let cml: Cml = (a, b) = > a + b
console.log(cml(1.2))  / / 3
Copy the code

Interface forms define functions

interface ICml {
  (x: number.y: number) :number
}

let cml: ICml = function(x: number, y: number) : number {
  return x + y
}
console.log(cml(1.2))  / / 3
Copy the code

2. Optional parameters

An optional parameter cannot be followed by a certain (must) parameter

function cml(x: number, y? :number) :number {
  y = y || 0
  return x + y
}
console.log(cml(1.2))  / / 3
console.log(cml(1))  / / 1
Copy the code

3. Remaining parameters

Recall argumenTypeScript for ES5 and argumentTypeScript for args ES5 for ES6

function cml() {
  let sum = 0
  for(let item of arguments) {
    sum = sum + item
  }
  return sum
}
console.log(cml(1.2.3)) / / 6
Copy the code

The args ES6

function cml(. args) {
  let sum = 0
  for(let item of args) {
    sum = sum + item
  }
  return sum
}
console.log(cml(1.2.3)) / / 6
Copy the code

Remaining arguments in TypeScript

function cml(. args:number[]) {
  let sum: number = 0
  for(let i: number = 0; i < args.length; i ++) {
    sum = sum + args[i]
  }
  return sum
}
console.log(cml(1.2.3)) / / 6
console.log(cml(1.'2'.3)) / / an error
Copy the code

4. Function overload

Function overloading in C++ : a function can have the same name but a different number of arguments, or the same number of arguments but a different type of argument. The compiler uses the number and type of arguments to determine which argument is called.

TypeScript functions are overloaded, and there is still only one function, but different parameter combinations can be statically typed

function cmlFun(arr: number[])
function cmlFun(arr: string[])
function cmlFun(arr: any[]) {
  if (typeof(arr[0= = =])'number') {
    return arr.reduce((pre, cur) => pre + cur)}else if (typeof(arr[0= = =])'string') {
    return arr.reduce((pre, cur) = > pre + cur)
  }
}
console.log(cmlFun([1.2.3])) / / 6
console.log(cmlFun(['1'.'2'.'3'])) / / 123
Copy the code

Four, class,

Classes and inheritance in ES6

/ / parent class
class Father {
  constructor (name, age) {
    this.name = name
    this.age = age
  }
}

/ / subclass
class Son extends Father{
    constructor(phone, ... args) {
        super(... args)this.phone = phone
    }
    f() {
        console.log('this.name'.this.name)
    }
}

let s = new Son('17807727381'.'parent'.'36')
s.f() / / this. The name of the father
Copy the code

1. Static keyword (ES6+)

Static Static properties and methods cannot be called using new.

class Father {
    static phone = '17723812637'
    static f() {
        console.log('this.phone'.this.phone)
    }
    constructor (name, age) {
      this.name = name
      this.age = age
    }
}
  
let fa = new Father('17807727381'.'parent'.'38')
fa.f() / / an error

Father.f()  // this.phone 17723812637
Copy the code

2. Public keyword

Attributes and methods that modify a class. Attributes and methods that are modified with public can be called inside or outside the class.

class Father {
  // Need to be defined first
  public name: string
  public age: number
  public constructor (name, age) {
    this.name = name
    this.age = age
  }
  public f() {
    console.log(this.name, this.age)
  }
}

let fa = new Father('parent'.36) // There are constructors, parameters can not be omitted
fa.f() / / parent class 36
Copy the code

3. Protected keyword

Protected properties and methods can only be accessed by classes or subclasses’ functions.

/ / parent class
class Father {
  protected name: string
  public age: number
  public constructor (name, age) {
    this.name = name
    this.age = age
  }
  f1() {
    console.log('this.name'.this.name)
  }
}

/ / subclass
class Son extends Father{
    public phone: string
    constructor(phone, ... args: [string.number]) {
        super(... args)this.phone = phone
    }
    f2() {
        console.log('this.name'.this.name)
    }
}
let fa = new Father('parent'.36)
fa.f1() // this. Name parent class (parent class accessed by function: OK)

let s = new Son('17807727381'.'parent'.36)
s.f2() // this. Name parent class (subclass accessed by function: OK)

let fa = new Father('parent'.36)
console.log(fa.name) / / an error
console.log(fa.age) / / 36
Copy the code

4. Private keyword

Properties and methods used to modify classes. Protected properties and methods are only accessible by class functions

/ / parent class
class Father {
  private name: string
  public age: number
  public constructor (name, age) {
    this.name = name
    this.age = age
  }
  f1() {
    console.log('this.name'.this.name)
  }
}

/ / subclass
class Son extends Father{
    public phone: string
    constructor(phone, ... args: [string.number]) {
        super(... args)this.phone = phone
    }
    f2() {

        console.log('this.name'.this.name)  / / an error}}let fa = new Father('parent'.36)
fa.f1() // this. Name parent class (parent class accessed by function: OK)

let s = new Son('17807727381'.'parent'.36)
s.f2() // Error (subclass access by function: not OK)

let fa = new Father('parent'.36)
console.log(fa.name) / / an error
console.log(fa.age) / / 36
Copy the code

5. Abstract keyword

Abstract classes: cannot be instantiated and cannot be directly new

abstract class Father {
  // Need to be defined first
  public name: string
  public age: number
  public constructor (name, age) {
    this.name = name
    this.age = age
  }
  public f() {
    console.log(this.name, this.age)
  }
}

let fa = new Father('parent'.36) / / an error
fa.f() 
Copy the code

The use of abstract methods. If a subclass inherits an abstract method from the parent class, it needs to implement the abstract method of the parent class in the subclass

abstract class Father {
  // Need to be defined first
  public name: string
  public age: number
  public constructor (name, age) {
    this.name = name
    this.age = age
  }
  public abstract f1(): void
}

class Son extends Father{
  public phone: string
  constructor(phone, ... args: [string.number]) {
    super(... args)this.phone = phone
  }
  public f2(): void {
    console.log('this.name'.this.name)
  }

  public f1(): void {
    console.log('this.name'.this.name)
  }
}

let fa: Father = new Son('17836762323'.'parent'.36)
fa.f1() / / this. The name of the father

Copy the code