简体   繁体   English

打字稿泛型语法:有什么作用<Type>达到?

[英]Typescript generics syntax: what does <Type> achieve?

Reading the typescript handbook on generics: https://www.typescriptlang.org/docs/handbook/2/generics.html阅读泛型打字稿手册: 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:我明白那个:

  1. arg: Type[] specifies the input argument. arg: Type[]指定输入参数。
  2. Type[] that comes before { ... } specifies the return type { ... }之前的Type[]指定返回类型

However,然而,

  1. What is the purpose of <Type> in loggingIdentity<Type> ? <Type>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). <Type>部分使它成为一个泛型:它定义了一个类型的变量(你可以命名任何你想要的名字,尽管TType是常见的)。 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.因此,您可以调用loggingIdentity(arg) ,其中arg的类型为numberstring或您想要的任何复杂类型。 The declaration with <Type> is what allows it;带有<Type>的声明是允许的; 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.并且在参数和返回类型中使用Type是您声明该方法将返回与传入的值类型相同的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM