打字稿中的泛型是什么? [英] What is Generics in Typescript?

查看:105
本文介绍了打字稿中的泛型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对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

这篇关于打字稿中的泛型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆