泛型 typescript

by Nadeesha Cabral

通过Nadeesha Cabral

如何把你的头围绕Typescript泛型 (How to wrap your head around Typescript generics)

Sometime back when the “Flow vs. Typescript” debate was raging, I had to pick a side. And I picked Typescript. Fortunately, that was one of the better decisions I made. When I had to make that decision, ultimately what convinced me was Typescript’s support for call-time generics.

有时在“流与打字稿”辩论激烈时,我不得不选择一方。 我选择了Typescript。 幸运的是,这是我做出的更好的决定之一。 当我不得不做出决定时,最终使我信服的是Typescript对呼叫时间泛型的支持 。

Today, let me try to walk you through what generics accomplish and how it helps us write safer, cleaner and more maintainable code.

今天,让我尝试引导您完成泛型的工作,以及它如何帮助我们编写更安全,更清洁和更可维护的代码。

示例1:声明一个简单类型 (Example 1: Asserting a simple type)

Let’s say we need a function that takes any value and puts that into an object. A naive implementation of this in Typescript would look and run like:

假设我们需要一个接受任何值并将其放入对象的函数。 在Typescript中对此的幼稚实现看起来和运行如下:

So much for type-safety.

对于类型安全来说,就这么多。

It’s true that myValue can be of any type. But what we need to tell the controller is that the output of the function, although it cannot be foreseen as the developer writing the code, can be “inferred” by the type of the input type. In other words, we can have a “generic definition” of what the output is.

确实myValue可以是任何类型。 但是我们需要告诉控制器的是,尽管开发人员无法编写代码,但可以通过输入类型来“推断”函数的输出。 换句话说,我们可以对输出内容有一个“通用定义”。

Generic implementation of the above function would be something like this:

上述功能的通用实现如下所示:

What we’re simply saying is that myValue can have a type of T. It can be “any type” but not any type. In other words, it has a type we care about.

我们只是在说myValue可以具有T的类型。 它可以是“任何类型”,但不能是any类型。 换句话说,它具有我们关心的类型。

If you try to write the earlier execution in Typescript, you won’t be able to run it, as the compiler gives a helpful warning:

如果尝试在Typescript中编写较早的执行,则将无法运行它,因为编译器会给出有用的警告:

示例2:使用泛型编写idx (Example 2: Writing idx with Generics)

idx is a “Library for accessing arbitrarily nested, possibly nullable properties on a JavaScript object”. It’s especially useful when you work with complex Javascript objects like REST API responses that may have nullable fields.

idx是“用于访问JavaScript对象上任意嵌套的,可能为空的属性的库”。 当您使用复杂的Javascript对象(如REST API响应,可能具有可为空的字段)时,此功能特别有用。

If you don’t mind me oversimplifying this a bit, it accomplishes this by basically trying the function given as the second parameter with props. If it fails, it catches and returns an undefined value safely, without throwing.

如果您不介意过分简化,它会通过基本try使用props作为第二个参数给出的函数来实现。 如果失败,它会catch es并安全地返回undefined值,而不会抛出异常。

Again, a naive implementation of this would be:

同样,此方法的简单实施是:

But, if we’re a bit clever with generics, we can get Typescript to help us with this.

但是,如果我们对泛型有点聪明,可以使用Typescript来帮助我们。

We’ve introduced two generics here.

我们在这里介绍了两个泛型。

T for the input type, and we “hint” that it’s an object by saying T extends {}. U is for the output type. And with these, we can express that the selector function is something that takes T and returns U of undefined.

T作为输入类型,我们通过说T extends {} “暗示”它是一个对象。 U是输出类型。 借助这些,我们可以表示selector函数是需要T并返回undefined的U的东西。

Now if you attempt to write the same code as before with this definition of idx, you will get a compile error:

现在,如果您尝试使用idx定义编写与以前相同的代码,则会出现编译错误:

示例3:使用类型推断和泛型获取函数的返回类型 (Example 3: Using type inference and generics to get the return type of a function)

Suppose that I have a function, and I need to supply the consumer with the type of output. If I call this type FooOutput, I’ll write something like:

假设我有一个函数,并且需要向消费者提供输出类型。 如果我将此类型FooOutput ,我将编写类似以下内容的内容:

But by using generics and type inference, I can write a ReturnType generic type, that can “infer” the return type of a function:

但是,通过使用泛型和类型推断,我可以编写一个ReturnType泛型类型,它可以“推断”函数的返回类型:

We’re playing with a T extends (...args: any[]) => any here. This just means that T is a generic function type that takes any number of any arguments and produces a value. Then we use it to infer another type R, and return it.

我们在这里玩一个T extends (...args: any[]) => any。 这只是个手段a吨T是一个通用的功能类型可以接收任意数量of任何参数,并产生一个值。 然后,我们用它to in FER另一个TY p éR,并将其返回。

Using this, I avoid the need to write my return type in the above example manually. Since foo is a function and I need that function’s type to use ReturnType, I’ve to get the type of foo by using typeof.

使用此方法,可以避免在上面的示例中手动编写我的返回类型。 由于foo是一个函数,我需要该函数的类型才能使用ReturnType ,所以我必须使用typeof来获取foo的类型。

工具箱中有用的实用程序? (Helpful utilities in my toolbox ?)

I use a bunch of these utilities in everyday programming. Most of the utility generics are defined in the typescript lib.es5.d.ts over here. Some of my most-used ones include:

我在日常编程中使用了许多此类实用程序。 大多数实用程序泛型都在此处的打字稿lib.es5.d.ts中定义。 我最常用的一些功能包括:

Hopefully, this helps you grasp Typescript generics a bit more. If you have questions, don’t hesitate to leave a question down below.

希望这可以帮助您更多地掌握Typescript泛型。 如果您有任何疑问,请不要在下面留下任何疑问。

翻译自: https://www.freecodecamp.org/news/how-to-wrap-your-head-around-typescript-generics-8d243f7de78/

泛型 typescript

泛型 typescript_如何把你的头围绕Typescript泛型相关推荐

  1. java 泛型应用,通用返回类,泛型方法,泛型静态方法

    java 泛型应用,通用返回类,泛型方法,泛型静态方法 泛型简介 应用示例 静态方法增加泛型参数 调用静态公有方法 对比调用非静态公有方法(成员方法) 泛型简介 这里不多说明,详见 java泛型入门 ...

  2. java泛型常用特点_?你必须知道的Java泛型

    前言 文本已收录至我的GitHub仓库,欢迎Star:https://github.com/bin3923282... 种一棵树最好的时间是十年前,其次是现在 我知道很多人不玩qq了,但是怀旧一下,欢 ...

  3. TypeScript - 泛型

    前言 本文主要记录下 TypeScript 泛型知识点,日常学习总结篇. 一.概念 泛型(Generics)是指在定义函数.接口或类的时候,不预先指定具体的类型,而在使用的时候再指定类型的一种特性. ...

  4. Part10 泛型程序设计与C++标准模板库 10.1泛型程序设计及STL的结构

    1泛型程序设计的基本概念 泛型程序设计: 编写不依赖于具体数据类型的程序 将算法从特定的数据结构中抽象出来,成为通用的 C++的模板为泛型程序设计奠定了关键的基础 术语:概念 用来界定具备一定功能的数 ...

  5. C++primer第十章 泛型算法 10.4 再探迭代器 10.5 泛型算法结构

    除了为每个容器定义的迭代器之外,标准库在头文件iterator中还定义了额外几种迭代器.这些迭代器包括以下几种. 插入迭代器(insert iterator):这些迭代器被绑定到一个容器上,可用来向容 ...

  6. TypeScript 泛型

    TS里面有泛型让我很意外,这个比AS3确实要强大: let myIdentity_change : <T>(arg:T)=>T=function(a){ return a };con ...

  7. 不正确 有三种形式 说法 通配泛型_一看就懂 详解JAVA泛型通配符T,E,K,V区别...

    1. 先解释下泛型概念 泛型是Java SE 1.5的新特性,泛型的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数.这种参数类型可以用在类.接口和方法的创建中,分别称为泛型类.泛型接口.泛 ...

  8. TypeScript泛型

    泛型的概念 指不预先确定的数据类型,具体的类型要在使用的时候才能确定.咋一听,是不是觉得JavaScript本身就是这样?这是由于理解有误.前面说"在使用的时候确定",而非在程序执 ...

  9. [.Net 4.0]泛型的协变,以及高阶函数对泛型的影响 Part 1

    按:这文章算是上星期与装配脑袋一起讨论到的一些东西的总结.我试图用更多一点的代码把协变和反变解释得更浅显一点.大家也可以参考Ninputer同学的文章: http://www.cnblogs.com/ ...

最新文章

  1. Autojs自动化 实现自动删除公众号文章(通过订阅号助手删除)
  2. 读阿里亿级日活网关通道架构演进有感
  3. win7远程多用户登录此计算机无法,win7如何实现远程桌面多用户登录|win7实现多用户登录远程桌面的方法...
  4. MySQL InnoDB Memcached Plugin在Oray公司的实践
  5. 捕捉Web页面子类错误堆栈中的信息
  6. 初学python-练习_1使用python编写计算班级学生平均分程序
  7. 洛谷1004方格取数
  8. Sublime Text 2 常用插件介绍
  9. 本特利177230-00-01-CN
  10. python 实现文字识别提取
  11. Python系统学习第二十四课
  12. Android之基于百度云推送IM
  13. [luogu]P1852跳跳棋
  14. java客服管理系统计算机毕业设计MyBatis+系统+LW文档+源码+调试部署
  15. Youtube推荐系统论文-《Deep Neural Networks for YouTube Recommendations》-简单总结
  16. 17互联网产品的交互设计(文智老师公开课笔记)
  17. JavaScript 原型链总结(一)
  18. 如何更改mysql数据库的用户名和密码
  19. 工艺库astro_使用Astro Pi航空箱为Raspberry Pi做好太空准备
  20. 买卖时机APP 开启股票交易大数据时代!

热门文章

  1. 事务相关命令 mysql
  2. 匿名内部类 java 1614965228
  3. django笔记精炼 200304
  4. web-使用wsgiref模块模拟web框架
  5. mysql数据库创建带-的数据库名
  6. -bash: ssh-copy-id: command not found解决方法
  7. (转)如何在maven的pom.xml中添加本地jar包
  8. virtualbox+vagrant学习-2(command cli)-15-vagrant resume命令
  9. PostgreSQL 逻辑订阅 - 给业务架构带来了什么希望?
  10. Hadoop单机模式安装入门(Ubuntu系统)