博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Typescript] Introduction to Generics in Typescript
阅读量:6300 次
发布时间:2019-06-22

本文共 1738 字,大约阅读时间需要 5 分钟。

If Typescript is the first language in which you've encountered generics, the concept can be quite difficult to understand. We skip the lecture in this lesson and dive straight into a real-world use-case that is guaranteed to help you understand the need for generics.

 

Let's say we have this part of code:

class Emitter{    emit(event){        console.log(event);    }}const emitter = new Emitter();emitter.emit({path: '/home', directory: true});

The object we want to pass in is {path: "", directory: ""}. But it may happen that we have some typo error, so we want IDE helps us to detect that.

 

TO do this, we need interface:

class Emitter
{ emit(event: MyEvent){ console.log(event); }}interface MyEvent{ path: string directory: boolean}const emitter = new Emitter
();emitter.emit({path: '/home', directory: true});

So it defines that the emit() function's param should have 'directory' and 'path' attrs. If not, it will report error.

 

So far so good, but what happen if we have anyother function inside the class, such as:

class Emitter
{ // T: allow everything come in emit(event: MyEvent){ console.log(event); } yield(value: MyValue){ console.log(value); }}interface MyEvent{ path: string directory: boolean}interface MyValue{ message: string}const emitter = new Emitter
();const yielder = new Emitter
();emitter.emit({path: '/home', directory: true});yielder.yield({message: "Hello World!"});

yield() take objet with message prop, and the interface defined as MyValue. So allows Emitter class accept multi interfaces, we can use <T>, then for each function, we add the interface for that.

转载地址:http://pagta.baihongyu.com/

你可能感兴趣的文章
关于HTTPOXY漏洞的分析说明
查看>>
最重要的就是做正确的事
查看>>
敏捷和架构设计分道而行,又最终拥抱彼此成为朋友
查看>>
用户故事 | 刷算法面试题的4种思考方式
查看>>
书评:《All About Java 8 Lambdas》
查看>>
在市场营销中使用敏捷方法:过程、团队与成功案例
查看>>
新书问答:Agile Management
查看>>
苹果将iOS应用带入macOS
查看>>
react入门
查看>>
NPM发布新的安全功能
查看>>
VUE高仿饿了么app
查看>>
针对Kubernetes软件栈有状态服务设计的思考
查看>>
中国在两年内赶超美国AI?李开复:不一定
查看>>
你的可用性达标了吗?云端业务性能高可用的深度实践
查看>>
恶意软件盯上了加密货币,两家以色列公司受到攻击
查看>>
苏宁11.11:苏宁双十一大促保障经验
查看>>
详解前端异步编程的六种方案
查看>>
Fin Goulding专访:在普世管理中注入敏捷
查看>>
使用反应式领域驱动设计来解决不确定性
查看>>
Sharding-Sphere成长记——写在分布式数据库代理端里程碑版本3.0.0发布之际
查看>>