At the heart of TS is the type system

Type annotations use the :TypeAnnotation syntax. Anything available in the type declaration space can be used as a type annotation. Type declaration keyword interface type

  • classThe space of a class declaration can be used as a type annotation
  • interface typeDeclared types cannot be used as variables
  • var let constThe space of such variable declarations cannot be annotated as a type

A simple type

The original type

Number String Boolean bigInt(typescript3.2) Symbol (typescript4.4)

Define the rules to use as follows: 👇

let num: number;
num = 123;
num = 123.456;
num = '123'; // Error

let symb: symbol;
symb = Symbol(1);
symb = Symbol('abc');
Copy the code

Special type

any undefined null void never unknow

any

Any is type-compatible in typescript and can be assigned to any type of data. This is used when JavaScript is migrating to typescript. Consider type protection during routine TS development and minimize the use of any types.

let power: any; let num: number = 21; // Assign any type of power = '123'; power = 123; power = num;Copy the code

Null, and undefined

By default null and undefined are subtypes of all types. Null and undefined can be assigned to any type. But with strictNullChecks enabled null and undefined can only be assigned to void and their respective types.

void

Void, as opposed to any, is not of any type and is often used in functions to indicate that there is no return value.

function fun(n:number):void {
    console.log(n);
}
Copy the code

💡 void variables can only be assigned to undefined or null, which is meaningless.

never

The never type represents a value that never exists, primarily for try.catch

unknow

Any type of data can be assigned to a variable of type unknown;

Data of unknown type can only be assigned to variables of unknown and any type.

Different from any is 👇

const n1:any = {
    foo: 'abc'
};
n1.foo;  // OK

const n1:unknown = {
    foo: 'abc'
};
n1.foo;  // ERROR: Property 'foo' does not exist on type 'unknown'.
Copy the code

The complex type

Array ancestor enumeration object

An Array of Array

First, use [] to specify the type, indicating that the elements in the array are of this type:

Let Numbers: (number) [] = [1, 2, 3, 4]; Let Numbers: (number | string) [] = [1, 2, 3, 4, '5'];Copy the code

The second is defined using the stereotype Array

Let Numbers: Array < number > = [1, 2, 3, 4, 5];Copy the code

Tuples Tuple

A meta-ancestor type represents an array of known data types (order) and number of elements.

const list1:[number, string] = [1, '2', 3]; // Error: only two variables const list2:[number, string] = [1, 2]; Const list3:[number, String] = ['1', 2]; // Error: the second element type is incorrect const list3:[number, String] = ['1', 2]; Const list4:[number, string] = [1, '2']; // Error: Two element types are reversed const list4:[number, string] = [1, '2']; // OKCopy the code

Enumeration (enum)

Enumerations are a way to organize the collection of associated variables, and TypeScript supports numeric and string-based enumerations. The numeric enumeration is more “reverse mapping” than the string enumeration.

Digital enumeration

enum Status { 
    CREATED,
    INPEOCESS,
    CLOSED
}
const status = Status.CREATED;
const created = Status[0];
Copy the code

By default, the CREATED value is 0, the rest of the members are +1, and 👇 is compiled

var Status;
(function (Status) {
    Status[Status["CREATED"] = 0] = "CREATED";
    Status[Status["INPEOCESS"] = 1] = "INPEOCESS";
    Status[Status["CLOSED"] = 2] = "CLOSED";
})(Status || (Status = {}));
var sts = Status.CREATED;
var created = Status[0];
Copy the code

You can set the default value or assign it manually.

enum Status { 
    CREATED = 1,
    INPEOCESS,
    CLOSED
}
enum Status { 
    CREATED = 2,
    INPEOCESS = 4,
    CLOSED = 6
}
Copy the code

String enumeration is similar to manual assignment in numeric enumeration.

Enum Status {CREATED = 'CREATED ', INPEOCESS =' under development ', CLOSED = 'CREATED'}Copy the code

The compiled

var Status; (function (Status) {Status["CREATED"] = "CREATED"; Status["INPEOCESS"] = "developing "; Status["CLOSED"] = "CLOSED"; })(Status || (Status = {})); var sts = Status.CREATED;Copy the code

Object (object)

Object is not used to define object types in TS. Instead, interfaces are used to annotate specific object types.

let o2:object = { a:1, b:2 };
Copy the code

Function (Function)

function sum(x: number, y: number): number { 
    return x + y 
}
let sum = function(x: number, y: number): number { 
    return x + y 
}
Copy the code

interface

Interface is a very important concept of TS, which is used to describe the shape of the object abstractly. You can use inline comments or interfaces

// Inline const person: {name: string; age: number; } = {name: 'name ', age: 18} age: number; } const person: person = {name: 'zhang3 ', age: 18}Copy the code

In addition, the interface can use the readonly property, which limits variables of this type to be assigned values only during initialization and cannot be changed later.

interface Person { name: string; readonly age: number; } const person: person = {name: 'person ', age: 18} person. Age ++; // ErrorCopy the code

When the interface attribute is optional, you can use? : to specify the type of the property

interface Person { name: string; age? : number; } const person: person = {name: 'person'}Copy the code

Type the alias

As the name implies, it is used to alias the type, defined by the keyword type. It has many similarities with interface, and will be explained in more detail later

type strType = string;
type Person = { 
    name: string;
    readonly age: number;
}
Copy the code

High-level types

The joint type

A | B said acceptable type A or type B.

let numStr: number | string;
numStr = '123';
numStr = 123;
Copy the code

Cross type

A & B indicates that an acceptable type must satisfy both A and B types.

interface IPerson { name: string age: number } interface IWorker { work: string; } type worker = IPerson & IWorker; Const workerPerson: worker = {name: 'cui花 ', age: 18, work: 'coding'}Copy the code

💡👉 is usually used for object types, and if you cross two different base types you get a never type. type nev = string & number; Equivalent to type nev = never

The index type

Use the index type query operator keyof T to get all the public attribute names of type T to form the union type.

class Person { name: string age: number private lover: String} type personKeys = keyof Person / / equivalent type personKeys = "name" | "age"Copy the code

Where T[K] is an index access that obtains the combined type of all the attributes of T that exist in K.

function pluck<T, K extends keyof T>(obj: T, keys: K[]): T[K][] { return keys.map(key => obj[key]) } interface Person { name: string age: number } let person: Person = { name: Pluck (person, ['name', 'age']) // Pluck (person, ['name', 'age'])Copy the code

Type STR = Person [‘ name ‘|’ age ‘] equivalent type STR = string | number

Mapping type

Syntax [K in Keys] and for… In is similar to iterating over all attribute names in a type.

type Keys = 'name' | 'hobby' 
type Person = {
    [K in Keys]: string 
}
Copy the code

Where Keys can be the attribute combination type obtained by keyof T, where T[P] is the current key type.

class Person { name: string age: number private lover: string } type personKeys = keyof Person type Optional<T> = { [P in keyof T]? : T[P] } type personType = Optional<Person> const testPerson: personType = { name: "test", age: 123} // type personType = Optional<Person> equivalent to 👇 // type personType = {// name? : string; // age? : number; / /}Copy the code

[P in keyof T]? : T[P] all set to optional attributes [P in keyof T]-? : T[P] All mandatory properties

paradigm

Generics is a template that allows the same function to take different types of arguments. Using stereotypes allows you to create reusable components like a component that supports multiple types.

Pass types as arguments to interfaces and functions

function identity <T>(value: T) : T { return value; } console.log(identity<Number>(1)); // 1 console.log(identity(hello)); / / hello console. The log (identity < Number > ([1, 2, 3])); / / [1, 2, 3]Copy the code
  • <T>Type variables can be set explicitly
  • identity(hello)It can also be set implicitly, with the compiler automatically selecting the type

Some common variable names

  • T(Type) indicates the TS Type
  • K(Key) indicates the Key type in the object
  • V(Value) indicates the Value type in the object
  • E(Element) indicates the Element type

Reference documentation

Exclude Extract Pick Omit

Exclude

type Exclude<T, U> = T extends U ? never : T
Copy the code

Exclude

Excludes from the union type T any union types that exist after the union type U.
,>

  • type N = Exclude<'a' | 'b' | 'c', 'a' | 'b' | 'c'>, the result is:type N = never
  • type E = Exclude<'a' | 'b' | 'd', 'b' | 'c'>, the result is:type E = 'a' | 'd'

Extract (Extract)

type Extract<T, U> = T extends U ? T : never
Copy the code

Extract

Extract the union type that exists in both the union type T and the union type U.
,>

  • type N = Extract<'a' | 'b' | 'c', 'd' | 'e'>And what we got this time istype N = never
  • type E = Extract<'a' | 'b' | 'd', 'b' | 'c'>And what we got this time istype E = 'b'

Pick up

type Pick<T, K extends keyof T> = {
    [P in K]: T[P]
}
Copy the code

Pick

or Pick

filters properties from object type T that exist in union type K to get the object type.
,>
,>

  • K extends keyof TIs to qualify the union typeKMust exist in the object typeTIn the
  • If the union typeKContains object typesTDoes not exist in. The resulting generated attribute type isunknown
interface IPerson { name: string age: Number} type pick = pick < IPerson, 'name' | 'age' | 'age1 > / / is equivalent to / / type pick = {/ / name: string; // age: number; // age1: unknown; / /}Copy the code

Omit anything

type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>
Copy the code

Omit

is to filter all attributes of the joint type K from object type T to obtain the object type.
,>

interface IPerson { name: string age: Number} type omitT = Omit<IPerson, 'name'> // omitT = {age: number; / /}Copy the code

Types of assertions

Type Assertion is a manually specified value Type.

as

let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Copy the code

Angle brackets

let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
Copy the code