For personal review, the sample code will not be parsed in detail


The original type


type grammar The characteristics of
Any type any Top-level type: represents all types and can be accepted by all types except never. Type detection cannot be performed when used. Abuse is not recommended
Void type void Null value, used when a function has no return value
Undefined type undefined Union types have undefined by default
Null type null There is no
Never type never Represents a value that does not exist. Is a subtype of all types
String type string Includes ES6 template strings
Numeric types number Support binary, octal, decimal, and hexadecimal
Boolean type boolean The value can be true or false
Unknown type unknown Top-level types: All other types can be accepted, but can only be assigned to any and unknown types themselves. Once compatible with other types, the code is checked against the corresponding type
object object Represents a non-primitive type, that is, a type other than number, string, Boolean, symbol, NULL, or undefined
Symbol type symbol Created through the Symbol constructor

An array of


There are two definitions: Type[] andArray<Type>   // Type = "Indicates the Type

const strArr: string[] = ['1'.'3']
const strArr2: Array<string> = ['1'.'3']

let fun = () = > 'str'
let arr: {(): string}[]  = [fun]   // Store functions that return a string value
let arr2: Array<() = > string>  = [fun]
Copy the code

tuples


Tuple types allow you to represent an array definition of the type of a known fixed number of elements: [Type1, Type2, Type3...]const address: [string, number] = ["Street".99];
Copy the code

The enumeration


Enumerations are a feature that provides more friendly names for constant data

Features: 1. Enumeration values have default numbers ascending from 0. You can set the initial value manually. 2. Enumeration values are constants and cannot be changed. 3. Enumerated values can be used as types

Digital enumeration

enum Num{
    ONE, //0 Is 0 by default
    TWO, / / 1
    THREE = 3 / / 3
}
Num.ONE / / 0
Num.THREE / / 3
Num[0] // ONE

// Create a numeric enumeration with calculated values
const num = 2
let fun = () = > 4

enum Calcuated {
    ONE = num,
    TWO = fun(),
    THREE = 3
}
Calcuated.THREE  / / 3
Calcuated.ONE   / / 2
Calcuated[4]   // TWO
Copy the code

String enumeration

enum Message {
    Error = 'Sorry, error',
    Success = 'Hoho, success',
    Failed = Error   // Use its own member
}
Message.Failed  // Sorry, error
Message.Error   // Sorry, error
Copy the code

Heterogeneous enumeration

Enumerations that use both strings and numbers are called heterogeneous enumerations

enum Result {
    Faild = 0,
    Success = 'success'
}
Copy the code

Enumerations are used as types

enum Animals {
    Dog = 1,
    Cat = 'success',}let a2:Animals.Cat = Animals.Cat
a2 //'success'
Copy the code

Constant enumeration

Constant enumeration, which is not compiled as a JS object. In some cases, performance can be improved

function


The function has two elements: defining the parameter type and the return value typelet fun: { (arg1: Type, argN: Type): Type} is equivalent tolet fun: (arg1: Type, argN: Type) = > Type

fun = (arg1: Type, argN: Type):Type= > {
    return TypeValue
}
Copy the code

Optional parameters

Optional arguments must follow the required arguments (arg1: Type, optional? : Type) => ReturnTypeCopy the code

The remaining parameters

(arg1: Type, ... Args: Type[]) => ReturnTypeCopy the code

The default parameters

Xx Type = default value of xx Type (arg1: Type = TypeValue,optional: Type = TypeValue) => ReturnType
Copy the code

overloading

Overloading allows a function to take different numbers or types of arguments and behave differently

1.TS functions that can be overloaded can only be usedfunction2. Overloading is divided into: function headers that are declared multiple times, and finally the function // overloaded part that actually processes all the function headersfunction overloadedMethod(arg1: Type) :ReturnType; 
function overloadedMethod(arg1: OtherType, arg2: OtherType) :ReturnType; // Handle overloaded functions specificallyfunction overloadedMethod(arg1: CommonType, arg2: CommonType) :CommonReturnType {} 

Copy the code

object


In TypeScript, as in JavaScript, objects consist of key-value pairs. We can assign types to object key-value pairs

let userData: { name: string, age: number } = {
    name: 'Max'.age: 27
  };
  
let complex: { data: number[], output: (all: boolean) = > number[] } = {
    data: [100.3.99.10].output: function(all: boolean) :number[] {
      return this.data
   }
};
Copy the code

interface


Features: 1. The data in the interface must be realized

The interface definition

Use interface keyword to define interface MyInterface {property: Type; optionalProp? : Type;// Optional attribute
    optionalMethod(arg1: Type): ReturnType; // Function definition
}
Copy the code

Interface inheritance

Features:1.Inheritable classclass SomeClass{}
interface Child extends SomeClass {
    
}
2.An interface can be inherited from a single interface or multiple interfaces simultaneouslyextends Parent {
    
} 
interface Child extends Parent1, Parent2 {
    
} 
Copy the code

Index signatures and read-only attributes

Read-only property: A property decorated with the readonly modifier. Features: can only be read, not modified. interface MyInterface { readonly property: Type; } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Index signature: contains only string and number signatures. Note: String index signatures are used. The return value Type of the remaining members must be the same as the string index (or the string index return value Type must be compatible with all other members). Interface MyInterface {[prop: String]: Type; [index: number]: Type; }Copy the code

The joint type


The union type indicates that the value can be one of many types.

Grammar: type | type2 | typeN...let a: string | number | boolean | {(): string }  
a = 'haha' //ok
a = 1 //ok
Copy the code

Type the alias


Use the type keyword to give a short name to a long list of code. type myType = string | number | boolean | {(): string }let a:myType = 1
a = 'kk'
let b:myType = true
Copy the code

Cross type


Cross typing is merging multiple types into one type.

interface Sex {
    sex: string
}
interface Person {
    name: string
    age: number
}
type SuperMan = Sex & Person;

const obj: SuperMan = {
    name: 'Bob'.age: 18.sex: 'man'
}
Copy the code

assertions


Bypass type detection1.<Type>Value <Type>Value2.asType the Valueas Type

let a = 1;
a.length //error 
(a as unknown as string).length // Assert to an unknown type, then assert to a string through an unknown type. Accessing the Length attribute will not report an error
Copy the code

Parsing of unknown types

class


The definition of a class

class SomeClass {
    property: Type;  // Define attributes
    readonly readProperty: Type; // Define read-only attributes
    defaultProperty: Type = 'default value'; // Attributes with default values
    constructor(Property: Type, readProperty: Type) {
        this.property = property    // Attribute assignment
        this.readProperty = readProperty
  }
   methodProperty: (arg1: Type) = > ReturnType; // Define the method
   
    overloadedMethod(arg1: Type): ReturnType; // Function overloading can also be defined internally
    overloadedMethod(arg1: OtherType): ReturnType;
    overloadedMethod(arg1: CommonTypes): CommonReturnTypes {} 

}
Copy the code

Attribute modifier

  • publicThe decorated property or method is public and can be accessed anywhere, as is the default for all properties and methodspublicthe
  • privateThe modified property or method is private and can only be accessed in the defined class. Not accessible externally and in subclasses
  • protectedA modified property or method is protected, similar to private, except that it is also accessible in subclasses
class SomeClass {
    public prop: Type;
    private prop1: Type; // Cannot be accessed by subclasses
    protected prop2: Type;
}
class Child extends SomeClass {
    constructor() {
        super(a)this.prop  
        this.prop2 } } ---------------------------------------------------------------------------------------------------------------------- Can be found inconstructorTo abbreviate instance properties using modifiers in.class SomeClass {
    constructor(public prop: Type} is equivalent toclass SomeClass {
    prop: Type;
    constructor(prop: Type){
        this.prop = prop
    }
}

Copy the code
  • use staticMethods modified by modifiers are called static methods; they cannot be instantiated, but are called directly from the class
class MyClass {
    staticreadonly prop? : Type;static staticProperty: Type;
    static fun() {
        
    }
}
MyClass.props
MyClass.fun()
Copy the code

inheritance

Inheritance: usingextendsThe keywordclass Parent {}
class Child extends Parent Implements interface MyInterface {}class Child implements MyInterface {} ------------------------------------------------------------------------------------------------------------------------ -- Special case: MyInterfaceextends Parent{} // If the interface inherits from the parent class
class Child extends Parent implements MyInterface {} // Subclasses need to inherit from the same parent class to implement the interface
Copy the code

accessor

ES6 knowledge, but TS also supports setting getters/setters to change the behavior of reading and assigning properties

Use get and set definitionsclass Animald {
    constructor(name) {
        this.name = name;
    }
    get name() {
        return 'Jack';
    }
    set name(value) {
        console.log('setter: '+ value); }}Copy the code

An abstract class

Abstract classes are base classes that other classes inherit from. Abstract classes are not allowed to be instantiated. Abstract methods in abstract classes must be implemented in subclasses

The keyword abstract defines the method abstract classes and subclasses need to implementclass Animal {
    constructor(public name) {
        this.name = name;
    }
    abstract sayHi();
    abstract get insideName() :string
    abstract set insideName(value: string)}new Animal('haha') / /error

class Dog extends Animal {
    sayHi(){}insideName:string
} 
Copy the code

Type of protection


1. Use the typeof to determine the base type string/number/one of the Boolean/symbol

if (typeof item === 'undefined') {
    console.log(item) 
} else { 
    console.log(item())    //error 
}
Copy the code

2. Use instanceof to judge classes

class Foo {
  foo = 123;
}

class Bar {
  bar = 123;
}

function doStuff(arg: Foo | Bar) {
  if (arg instanceof Foo) {
    console.log(arg.foo); // ok
    console.log(arg.bar); // Error
  } else {
    // In this block, it must be 'Bar'
    console.log(arg.foo); // Error
    console.log(arg.bar); // ok}}Copy the code

3. Use the in operator to safely check whether an attribute exists on an object

interface A {
  x: number;
}

interface B {
  y: string;
}

function doStuff(q: A | B) {
  if ('x' in q) {        // In is similar to the for in loop, which iterates over properties on the object
    // q: A
  } else {
    // q: B}}Copy the code

4. User-defined type protection

// Just an interface
interface Foo {
  foo: number;
  common: string;
}

interface Bar {
  bar: number;
  common: string;
}

// Self-defined type protection!
function isFoo(arg: Foo | Bar) :arg is Foo { // is is the keyword
  return (arg asFoo).foo ! = =undefined;
}

// Use case of type protection:
function doStuff(arg: Foo | Bar) {
  if (isFoo(arg)) {
    console.log(arg.foo); // ok
    console.log(arg.bar); // Error
  } else {
    console.log(arg.foo); // Error
    console.log(arg.bar); // ok}}Copy the code

5. Literal type protection: mainly used to judge union types

type Foo = {
  kind: 'foo'; // The literal type
  foo: number;
};

type Bar = {
  kind: 'bar'; // The literal type
  bar: number;
};

function doStuff(arg: Foo | Bar) {
  if (arg.kind === 'foo') {
    console.log(arg.foo); // ok
    console.log(arg.bar); // Error
  } else {
    // It must be Bar
    console.log(arg.foo); // Error
    console.log(arg.bar); // ok}}Copy the code

The generic


Generics are the feature of defining functions, interfaces, or classes without specifying a specific type in advance.

A generic class

Create a generic class T, which is a type placeholder, with the arbitrary name a, B, c, d....class Queue<T> {T captures the type of input. Private data :T[] = []; push =(item: T) = > this.data.push(item);
  pop = (): T | undefined= > this.data.shift(); } Simple to useconst queue = new Queue<number>();
queue.push(0);
queue.push('1'); // Error: Cannot push a string, only number is allowed-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - can be set only to internal members generics, when use the incoming typeclass Utility {
  reverse<T>(items: T[]): T[] {
    const toreturn = [];
    for (let i = items.length; i >= 0; i--) {
      toreturn.push(items[i]);
    }
    returntoreturn; }}const child = new Utility()
child.reverse<number>([1.2.3.5])
// Use TS type inference shorthand
child.reverse([1.2.3.5])  // T[] === <number>[]
Copy the code

Generic function

function reverse<T> (items: T[]) :T[] {
  const toreturn = [];
  for (let i = items.length - 1; i >= 0; i--) {
    toreturn.push(items[i]);
  }
  return toreturn;
}

const sample = [1.2.3];
let reversed = reverse(sample);  // TS will infer that T is type number. T[] === 
      
       []
      

reversed[0] = '1'; // Error
reversed = ['1'.'2']; // Error

reversed[0] = 1; // ok
reversed = [1.2]; // ok

Copy the code

A generic interface

Interface Pair<T, U> {first: T;
  second: U;
}

let pair:Pair<number,string> = {
    first: 1.second: '2'
}
Copy the code

Generic constraint

useextendsInterface Lengthwise {let the generic inherit some conditions to achieve the effect of constraintlength: number; } The parameter type passed in must have a length attributefunction loggingIdentity<T extends Lengthwise> (arg: T) :T {
    console.log(arg.length);
    return arg;
}

loggingIdentity(7)   // error 
loggingIdentity([1.2.3.4])  //ok
loggingIdentity('111')   //ok
loggingIdentity({     
    length: 6       //ok}) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- each other between generic constraintfunction copyFields<T extends U.U> (target: T, source: U) :T { //T inherits U, so T must contain attributes in U
    for (let id in source) {
        target[id] = (<T>source)[id];
    }
    return target;
}

let x = { a: 1.b: 2.c: 3.d: 4 };
let y = { a: 1.b: 2.c: 3};
copyFields(x, { b: 10.d: 20 });   // ok
copyFields(y, { b: 10.d: 20 });   // error
Copy the code

The default type of a generic parameter

This default type comes into play when type parameters are not specified directly in the code when using generics and cannot be inferred from the actual value parameters.function createArray<T = string> (length: number, value: T) :Array<T> {
    let result: T[] = [];
    for (let i = 0; i < length; i++) {
        result[i] = value;
    }
    return result;
}
Copy the code

Keyof Index type query operator

Keyof joins to a type and returns a combined type consisting of all the attribute names of that type

interface Info {
    name: string;
    age: number;
}
let infoProp: keyof Info  
/ / equivalent to let infoProp: 'name' | 'age' literal type

infoProp = 'name'  //ok
infoProp = 'age'   //ok
infoProp = 'sex'   //error
//----------------------------------------------------------------------------------------------------

interface Type1 {
   a: string;
   b: number;
   c: never;
   d: null;
   e: undefined;
   f: object;
}
type Test3 = Type1[keyof Type1] // The filter attribute value is never,null,undefined
Test3 // stirng | number | object

//----------------------------------------------------------------------------------------------------

declare class Person {
  private married: boolean;
  public name: string;
  public age: number;
}

let publicKeys: keyof Person;
/ / equivalent to let publicKeys: "name" | "age"
// Only public attributes can be obtained

// ------------------------------------------------------------------------------------------------------

Copy the code

Index access operator: []

The index access operator returns the type of the attribute value: interface Info {name: string;
    age: number;
}
type InfoNameType = Info['name']  // Return the type of name: stringEquivalent to type InfoNameType = stringCopy the code
/ / K is now save all the properties of the T in the form of joint types exist | | xx xx xx...
function getValue<T.K extends keyof T> (obj: T, names: K[]) :Array<T[K] >{ / / the return value type Array < string | number >
    return names.map((n) = > obj[n])
}
const infoObj = {
    name: 'lison'.age: 18,}let infoValues: Array<string | number> = getValue(infoObj, ['name'.'age'])
Copy the code

Prefix modifier: + –

Readonly or? Attribute modifiers can now be prefixed with + or – to indicate whether modifiers are added or removed.

interface Info1 {
  age: number;
  name: string;
  sex: string;
}
Add the readonly modifier in front of the property.
type ReadonlyType<T> = {
  / / keyof T get all the properties of T age | name | sex
  // in is similar to for.. The in loop iterates through these properties
  readonly [P in keyof T]: T[P]
  
  / / equivalent to the
  // + readonly [P in keyof T]: T[P]
  // There is a prefix + to add the readOnly modifier.
}
type ReadonlyInfo1 = ReadonlyType<Info1>
// Now ReadonlyInfo1 attributes are read-only.
// ReadonlyInfo1 has the following type structure: ↓
// type ReadonlyInfo1 = {
// readonly age: number;
// readonly name: string;
// readonly sex: string;
// }



// Now remove the readonly modifier
type RemoveReadonlyInfo2<T> = {
   - readonly [P in keyof T]: T[P]
   Readonly is preceded by a - sign. Represents removing the readonly modifier before the property
}
type Info1WithoutReadonly = RemoveReadonlyInfo2<ReadonlyInfo1>
// Remove readOnly
// Info1WithoutReadonly now type structure: ↓
// type Info1WithoutReadonly = {
// age: number;
// name: string;
// sex: string;
// }

Copy the code