TypeScript full interpretation

This article is a project's look at typescript from the ground up. Feel free to comment on any mistakes or inadequacies. Continuously updated...

1. Initialization

  • Initialization project: npm init -y
  • Global install TS dependency:npm install typescript tslint -g
  • Ts initialization:tsc --init
  • Install webpack:npm install webpack webpack-cli webpack-dev-server -D

2. Install the vscode plug-in

  • TSLint
  • TSLint (deprecated)
  • TSLint Vue
  • TSLint Snippets
  • TSLint Vue-TSX
  • Json to TS Directly generates THE TS type from JSON data
  • Settings Sync Settings are saved on Github
  • Image preview tool: Image Preview

3. Basic types of TS

3.1. Boolean values (as in other languages)

let isDone: boolean = false;

3.2. Numbers (all numbers in TS are number types)

Let num: number = 123 num = 12.3 num = 0b11; num = 0o111; num = 0x11;Copy the code

3.3. String type (you can use double, single, or backquotes to represent strings)

let num1 = 12 let str: string; str = 'abc'; STR = 'value: ${num1}'Copy the code

3.4. Array types (there are two definite forms, one is to add [] after the element type, and the other is to use the generic Array[element type])

[] let arr1: number[]; let arr2: (string | number)[]; // Use generic Array[element type] let arr3: Array<number>; let arr4: Array<string | number>; // call arr1 = [1]; arr2 = [1, 'a']Copy the code

3.5. Tuple type (represents an array with a known number and type of elements. The elements need not be of the same type)

let tuple: [string, number, boolean];
tuple = ['a', 1, false]
Copy the code

3.6. Enumeration type (no initial value set, automatically starts from 0, default value can also be customized)

enum Roles {
    ADMIN,
    USER = "admin",
}
Copy the code

3.7. Any type (use as little as possible, otherwise TS will be completely worthless)

let value:any = 'abc'

3.8. Void type (no return value default return value is undefine)

Void is in some ways the opposite of any; Also, declaring a void type doesn’t make much sense because it can only assign undefined and null

const consoleText = (text: string): void => {
    console.log(text)
}

let unable:void = undefined | void;
Copy the code

3.9. Null and undipay type (which are sub-types of all types, the other values can be assigned either Null or undefined)

let u: undefined;
u = undefined;
let n: null;
n = null;
Copy the code

Error types and infinite loops generally throw Never types

// never is a non-existent type const errorFun = (message: string): Const infiniteFunc = (): never => {while (true) {}}Copy the code

Object represents a non-primitive type, that is, a type other than number, string, Boolean, symbol, NULL, or undefined.

3.12 Assertions (Identified Types) Assertions come in two forms: an Angle bracket syntax; An AS syntax

Const getLenght = (target: string | number) => { if ((<string>target).length || (target as string).length === 0) { return (target as string).length  } else { return target.toString().length } }Copy the code

Note: When using JSX in TypeScript, only AS syntax assertions are allowed.

3.13 symbol type

  • Symbol is a new type that represents unique values
  • The value of symbol cannot be manipulated with other data types

4. The function

Functions can be defined in two ways: using literals and the keyword Function

const func = funct(){}
function func(){}
Copy the code

5. Advanced types

5.1 Crossing Types Crossing types generally use the ampersand symbol to join two types. Value relative to the union.

const mergeFunc = <T, U>(arg1: T, arg2: U): T & U => {
  // let res = {} as T&U;
  // let res = <T&U>{};
  let res = Object.assign(arg1, arg2);
  return res;
Copy the code

5.2 the joint type General use | symbols to identify joint type. Equivalent to or

let number: string | number; Const getLengthFunc = (content: string | number) => { if (typeof content === "string") return content.length; else return content.toString().length; };Copy the code

5.3 Type Protection Law Generally, when there are more than two types of protection law, the system determines the type, which results in type errors. There are usually typeof and instanceof type determination statements.

  • Typeof: can only be an equal or unequal operation. Other rules do not provide type protection. The type of an operation (eng) is one of the following four types:string/number/boolean/symbol
  • Instanceof type protection effect can be used other than the above four types.

5.4 Type Determination Usage in the development process, determine a type is what, but the editor will still report an error, this can be used! Symbol to use a type assertion to indicate that it must be this type.

The function getSplicedStr (num: number | null) : string {function getRes (prefix: string) {/ /! Return prefix + num! .toFixed().toString(); } num = num | | 0.0; return getRes("sub_"); }Copy the code

5.5 String Literal Types Use string literals to define types in some identified types, avoiding types other than literals. Numeric literal types are basically similar to string class literals.

/ / defines the Direction of a string literal type type Direction = "north" | | "east" "south" | "west"; Function getDirectionFirstLetter(direction: direction): string {return direction.substr(0, 1); function getDirectionFirstLetter(direction: direction): string {return direction.substr(0, 1); } // The call can only enter the defined literal type getDirectionFirstLetter(" North ");Copy the code

5.6 Identifiable union type Two elements of the identifiable union type are as follows:

    1. Has common singleton type attributes;
    1. A type alias contains the union of those types

Here is an example of finding the area of a circle, rectangle or rectangle:

Interface Square {kind: "Square "; size: number; Rectangle {kind: "Rectangle "; height: number; width: number; } // Define a circular interface Circle {kind: "Circle "; radius: number; } / / three types of interface is defined as a string literal type, type, Shape = Square | Rectangle | Circle; // None other than the above three types. Function asserNever(value: never): never {throw new Error("Unexpected Object: "+ value); } function getArea(s: Shape): number {switch (s.type) {case "square": return s.size * s.size; case "rectangle": return s.height * s.width; case "circle": return Math.PI * s.radius ** 2; default: return asserNever(s); }}Copy the code

5.7 Index Type The index type is divided into two parts: index type query and index access.

  • Indexing query
    • Index queries use operatorskeyofA union type that can generate a literal type.

  • Index access
    • Index access uses operators[]Can get a single attribute value or a group of attribute values

5.8 Mapping Type Mapping type: An old type can be converted to a new type.

Several built-in methods are provided in the mapping: ReadOnly, Partail, Pick, record

  • Readonly: Changes all properties to read-only

    type inner_readOnly = Readonly<oldInfoType>;

  • Partail: Makes all data optional

    type inner_readOnly = Partail<oldInfoType>;

  • Pick: obtains some attributes of an object

  • recordApplies to converting every property in an object to another worthy scene

5.9 Adding or Removing Specific modifiers You can use + and – to add or remove special modifiers. The default is to add +

type oldInfoMap<T> = {
 + readonly [P inkeyof T]-? : T[P];// in indicates a loop
};

Copy the code

5.10 unknown type

  1. Any type can be assigned to an unknown type

    let value1: unknown;
    value1 = 11;
    value1 = "aaa";
    Copy the code
  2. If there is no type assertion or type refinement based on control flow, unknown cannot be assigned to any other type. In this case, it can only be assigned to unknown itself and any type.

    let value2: unknown; // error: Cannot assign type "unknown" to type "string" // let value3:string = value2;Copy the code
  3. Nothing can be done on it without type assertion or type refinement based on control flow

    let value4: unknown; // error: The object type is "unknown" // value4+=1;Copy the code
  4. An intersection type of unknown with any other type that ends up equal to the other type

    type type1 = string & unknown;
    type type2 = number & unknown;
    type type3 = unknown & unknown;
    type type4 = string[] & unknown;
    Copy the code
  5. A combined type of unknown with any other type except any is equal to the unknown type

    type type5 = string | unknown;
    type type6 = any | unknown;
    type type7 = string[] | unknown;
    Copy the code
  6. The never type is a subtype of unknown

    type type8 = never extends unknown ? true : false;
    Copy the code
  7. Keyof unknown is the type never

    type type9 = keyof unknown;
    Copy the code
  8. Only equal or unequal operations can be performed on Unknown

    value1 === value2; value1 ! == value2;Copy the code
  9. A value of type unknown cannot access its properties, be called as a function, or create an instance as a class

    let value10: unknown;
    // value10.name= ''
    // value10()
    // new value10()
    Copy the code
  10. If the mapping type is traversed through the unknown type, no attributes are mapped

    type types1<T> = {
      [P in keyof T]: number;
    };
    type type10 = types1<any>;
    type type11 = types1<unknown>;
    
    Copy the code

5.11 Condition Type Example: T extends U? X : Y

Type types2

= T extends string? string : number; Type Type14

= T extends Array

? U : T;


Some built-in types of methods: Exclude, Extract, NonNullable, ReturnType.

  • Exclude

    Returns an entry in U that is not in T
    ,u>

type Type15 = Exclude<"a" | "b" | "c", "a" | "b">;

  • Extract

    Extract the intersection of T and U
    ,u>

type Type16 = Extract<"a" | "b" | "c", "a" | "v">;

  • NonNullable Removes null and undefined

type Type17 = NonNullable<string | number | null | undefined>;

  • ReturnType Gets the return value type

type Type18 = ReturnType<() => string>;