Generics are essentially a type, an indeterminate type. Generics are commonly understood as a type that addresses the reuse of classes, interfaces, methods, and support for unspecified and future types. Because of uncertainty, generics are vague and abstract. For example, there is a requirement to get a value passed in by the user

// Both the incoming type and the return type are strings
function getDate(value: string) :string {
    return value;
}

// Both the incoming type and the return type are number
function getDate1(value: number) :number {
    return value;
}
Copy the code

The above two methods can only pass values of type number and string, and have to call different methods, resulting in redundant code. Generics came in, and we could write it like this

// T is a generics, a function that returns all types
function getDate<T> (value: T) :T {
    return value;
}

let a = getDate<number> (100) / / number type
let b = getDate<string> ("hello") / / type string
let c = getDate<Boolean> (true) / / booleam type.// Other types

console.log(a)
console.log(b)
console.log(c)
Copy the code

It has been said that using any can achieve the same effect, but remember that when using any, you abandon typescript type validation, which does not conform to the typescript specification.