Constructor -> Construct Signatures

interface CallOrConstruct { new (s: string): Date; (n? : number): number; }function fn(ctor: CallOrConstruct) { return new ctor("hello"); }Copy the code

Generic function

function firstElement<Type>(arr: Type[]): Type { return arr[0]; }Copy the code

Inference – > inference

TS according to

function map<Input, Output>(arr: Input[], func: (arg: Input) => Output): Output[] { return arr.map(func); } // Parameter 'n' is of type 'string'// 'parsed' is of type 'number[]'const parsed = map(["1", "2", "3"], (n) => parseInt(n));Copy the code

Constraints – > Constraints

extends

Sometimes, when you want to associate two values. However, only a subset of values can be manipulated.

function longest<Type extends { length: number }>(a: Type, b: Type) {  if (a.length >= b.length) {    return a;  } else {    return b;  }}
Copy the code

Constraint value

The following code fails because the function guarantees an object of the same type as the passed argument, rather than an object that conforms to the constraint.

function minimumLength<Type extends { length: number}>(
    obj: Type, 
    minimum: number
): Type{
    if (obj.length >= minimun){
        // Type '{ length: number; }' is not assignable to type 'Type'.
        // '{ length: number; }' is assignable to the constraint of type 'Type',
        //  but 'Type' could be instantiated with a different subtype of constraint '{ length: number; }'.
        return obj
    }else{
        return { length: minimum }
    }
}
Copy the code

Specifying Type Arguments

function combine<Type>(arr1: Type[], arr2: Type[]): Type[]{ return arr1.concat(arr2); Const arr = combine([1, 2, 3], ["hello"]); // Combine ([1, 2, 3], ["hello"]); / / solution const arr = combine < string | number > ([1, 2, 3], [" hello ");Copy the code

Push Type Parameters Down

Avoid overuse of constraints in generics

function firstElement1<Type>(arr: Type[]){ return arr[0] } function firstElement2<Type extends any[]>(arr: Type){return arr[0]} // return number const a = firstElement1([1,2,3]) // Type extends any return any const b = FirstElement2 ([1, 2, 3])Copy the code

Use Fewer Type Parameters

The second is unnecessary. Extends is actually a generic variable joining two values that “share” the generic variable.

function filter1<Type>(arr: Type[], func: (arg: Type) => boolean): Type[]{
    return arr.filter(func)
}

function filter2<Type, Func extends (arg: Type) => boolean>(
    arr: Type[],
    func: Func
): Type[]{
    return arr.filter(func)
}
Copy the code

The original: We’ve created a type parameter Func that doesn’t relate two values. That’s always a red flag, because it means callers wanting to specify type arguments have to manually specify an extra type argument for no Reason. Func doesn’t do anything but make the function harder to read and reason about!

Type Parameters Should Appear Twice

Sometimes we forget that a function might not need to be generic:

function greet(s: Str) {

    console.log(“Hello, ” + s);

}

Type Parameters Should Appear Twice

Generics are used to relate types with multiple values. It is best not to use type parameters if they occur only once in a function.

Remember, type parameters are for relating the types of multiple values. If a type parameter is only used once in the function signature, it’s not relating anything.

Optional Parameters

? The symbol represents an optional argument, and the function below may pass undefined or no number

declare function f(x? : number): void; f(); f(10); f(undefined);Copy the code

In the callback function, index is optional; If I is passed into cb, an error will be reported. It can be avoided.

function myForEach(arr: any[], callback: (arg: any, index? : number) => void){ for (let i = 0; i < arr.length; I++) {callback (arr) [I]}} myForEach ([1, 2, 3], (a, I) = > {the console. The log (I! Object is possibly 'undefined'. // console.log(i.tofixed ())})Copy the code

However, if cb is passed two parameters and only one parameter is passed, no error will be reported. In this case, TS behaves the same as JS.

Function overload Function Overloads

When overloaded, the type of the parameter must be determined, not ambiguous, as follows.

function len(s: string): number; function len(arr: any[]): number; function len(x: any) { return x.length; } len(""); // OKlen([0]); // OK len(math.random () > 0.5? "hello" : [0]); // Error reported because the value is differentCopy the code

Declare this in the function

TS will derive the value of this

interface User{ id: number; admin: boolean } interface DB { filterUsers(filter: (this: User) => boolean): User[]; } declare const getDB: () => DB; const db = getDB(); const admins = db.filterUsers(function(this:User) { return this.admin })Copy the code

Other types of

Void: void is not undefined

Object: In TS, object refers to non-basic objects. Is not a plane {}

Unknow: Similar to any, but more secure because you cannot do anything with the unknown type

Never: In functions, never indicates that the function will report an error or terminate execution. It also means that there are no other types in the union type

Function: Funcion returns any, more:

reference

www.typescriptlang.org/docs/handbo…