Reading the typescript handbook on generics: https://www.typescriptlang.org/docs/handbook/2/generics.html
I got confused on the syntax for below example:
function loggingIdentity<Type>(arg: Type[]): Type[] {
console.log(arg.length);
return arg;
}
I understand that:
arg: Type[]
specifies the input argument. Type[]
that comes before { ... }
specifies the return type However,
<Type>
in loggingIdentity<Type>
? What does it achieve?
The <Type>
part is what makes it a generic: it defines a variable of sorts (which you can name anything you want, though T
or Type
are common). This is the placeholder for any type.
So you can call loggingIdentity(arg)
where arg
is of type number
or string
or any complex type you want. The declaration with <Type>
is what allows it; and the usage of Type
in the argument and the return type is your declaration that the method will return the same type of value as was passed in.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.