TS study notes

TypeScript

1 type base

1.1 Primitive data types

Boolean, string, number, void, null, undefined, Symbol, BigInt
Note:
1. Null and undefined are subsets of all types.
2. The object created by the constructor is essentially an object. The following code will report an error.

let createdByNewBoolean: boolean = new Boolean(1);

// Type 'Boolean' is not assignable to type 'boolean'.
//   'boolean' is a primitive, but 'Boolean' is a wrapper object. Prefer using 'boolean' when possible.

3. void is used to define a function with no return value. If it is used to define a variable, it can only be assigned undefined/null, which does not make much sense.

2.2 Define object types

ts uses interfaces to define objects. On the one hand, it constrains the type of object properties, and on the other hand, it constrains the shape of objects (the number of interface properties must be fully followed).

interface Person {
    
    
    name: string;
    age: number;
}

let tom: Person = {
    
    
    name: 'Tom',
    age: 25
};

1. Optional attribute: add a question mark after the attribute name.
2. Arbitrary attribute: After any attribute is defined, the definite attribute and optional attribute must be a subset of it.
3. Read-only attribute: put readonly before the attribute name. The property cannot be reassigned, but it should be noted that the read-only constraint exists when the object is assigned a value for the first time, not when the read-only property is assigned a value for the first time.
Note: The first letter of the interface is generally capitalized, and the official recommended interface name starts with I to be clearer

2.3 Define the array type

1. Type + square bracket definition.
2. Array generic: Array<type>
3. Interface representation array: the essence of an array is an object, just define the index as a number.

interface NumberArray {
    
    
    [index: number]: number;
}
let fn: NumberArray = [1, 1, 2, 3, 5];

This definition method mostly exists in class arrays. For example, the arguments of a function are class arrays. You can use the length of the array and use subscripts to get items, but you cannot use any array methods, such as arr.sort(), and its It has an attribute callee, which points to the current function. At this point you need to use the interface to define.

interface IArgs{
    
    
[index: number]: number;
        length: number;
        callee: Function;
}
function sum() {
    
    
    let args: IArgs = arguments;
}

2.4 Define function type

1. Type constraints need to be imposed on the parameters and return values ​​of the function.

let mySum: (x: number, y: number) => number = function (x: number, y: number): number {
    
    
    return x + y;
};

Often the type declaration on the left can be omitted, because it will automatically derive the type through type inference.
2. Interfaces can be used to define functions

interface SearchFunc {
    
    
    (source: string, subString: string): boolean;
}

let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
    
    
    return source.search(subString) !== -1;
}

3. Note:
(1) You can write optional parameters, just add a question mark after it. But it must be written in the order of required parameters > optional parameters. If a parameter is set with a default value, it is considered an optional parameter and is not limited by mandatory parameters > optional parameters.
(2) The remaining parameters are an array, which can be defined in the form of an array
(3) The overload of the function can use the joint type declaration to limit the type of parameters

function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string | void {
    
    
    if (typeof x === 'number') {
    
    
        return Number(x.toString().split('').reverse().join(''));
    } else if (typeof x === 'string') {
    
    
        return x.split('').reverse().join('');
    }
}

The meaning of the first two codes is to clarify that when the input is a number, the output must also be a number, etc. TypeScript will give priority to matching from the first function definition, so if multiple function definitions have inclusion relationships, you need to write the precise definition first.

2 Basic concepts

2.1 Type inference

The variable is only assigned an initial value but does not specify a type when it is defined, and ts will automatically infer the type and verify it in subsequent operations. Of course, if no value is assigned during definition, it will default to any and not be checked.

2.2 Union types

The value can be one of many types, and different types are separated by |.
If the variable is not assigned a value and it is uncertain which type it is, only the properties or methods common to all types can be accessed.

2.3 Type Assertions

The value as type
can skip the compiler's verification, that is, the editor specifies what type is here, and informs ts to treat it as this type without verifying the value. Purpose: No syntax error will occur after clarifying the type of assertion here.

  • A union type can be asserted as one of the types
  • A parent class can be asserted as a child class
  • Any type can be asserted as any
  • any can be asserted as any type
  • To enable A to be asserted as B, only A is compatible with B or B is compatible with A

Guess you like

Origin blog.csdn.net/m0_46550764/article/details/126075237