打字稿中的泛型是什么?
我对Typescript完全陌生,以前从未接触过C#或Java.
因此,即使我在官方打字稿网站上阅读了说明,我也真的不理解Generics
的真正用法.
I am totally new to typescript and never into c# or java before.
So even if I read the instruction on official typescript website, I really do not understand the real use of Generics
.
这是Generics
的简单示例.下面执行此操作的真正好处是什么?
Here is the simple example of Generics
. What is the real benefits of doing this below?
function identity<T>(arg: T): T {
return arg;
}
var output = identity<string>("myString");
没有泛型,我可以在下面这样做(或者我可以使用Interfaces确保传递指定的参数.)
without Generics, I can just do this way below (or I can use Interfaces to make sure to pass specified arguments.)
function identity(arg: any): any {
return arg;
}
var output = identity("myString");
任何建议将不胜感激. 谢谢
Any advice would be appreciated. Thank you
仅从您的基本示例开始:
Just going from your basic example:
function identity<T>(arg: T): T {
return arg;
}
在此处具有通用 会在自变量(arg:T
)和返回类型: T{
之间强制执行约束.这使编译器可以从参数推断出返回类型,如下所示:
Having a generic here enforces a constraint between the argument (arg:T
) and the return type : T{
. This allows the compiler to infer the return type from the argument as shown below:
function identity<T>(arg: T): T {
return arg;
}
let str = identity('foo');
// str is of type `string` because `foo` was a string
str = '123'; // Okay;
str = 123; // Error : Cannot assign number to string