TypeScript of generics

What is generic, what's the use?

 Literally means a wide range of generic type, widely considered how to do? Of course, it can become the most widely thing,

The so-called generic variable is the type of wording, make your variable type is dynamically variable, as the example scenarios described in official documents:

A function, what type of input, outputs what type, as follows:

function identity<T>(arg: T): T { return arg; }

Generic use declare variables (<type>) in <> are used within the scope

Function: function  Identity < T> ( Arg: T):  T {  return Arg;}

Interface: interface GenericIdentityFn <T> {(Arg: T): T;}

类中:class GenericNumber<T> { zeroValue: T; add: (x: T, y: T) => T; }

Generic constraints

interface Lengthwise { length: number; }

function loggingIdentity<T extends Lengthwise>(arg: T): T {

console.log(arg.length);

// Now we know it has a .length property, so no more error return arg;

}

 

Guess you like

Origin www.cnblogs.com/superjsman/p/11807165.html