[Typescript] Introduction to Generics in Typescript
2016-04-29 03:47
337 查看
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:
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:
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:
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.
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<MyEvent>{ emit(event: MyEvent){ console.log(event); } } interface MyEvent{ path: string directory: boolean } const emitter = new Emitter<MyEvent>(); 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>{ // 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<MyEvent>(); const yielder = new Emitter<MyValue>(); 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.
相关文章推荐
- mongo 分片Replica Sets+Sharding架构
- LeetCode 238
- LeetCode 42
- 【Swift学习】Swift编程之旅---属性(十四)
- 用Base64加解密时发现的问题(其实时java基础问题byte[]转String)
- jiffies的回绕问题及解决方案
- 51Nod-1134-最长递增子序列
- winform异步线程防止界面卡死
- 3-Java控制语句、循环、函数
- Linus,一生只为寻找欢笑(完全版)
- HandlerThread 的基本使用
- python字符串相关操作
- Winform datagridview绑定问题
- Codeforces #325 Div2 C Gennady the Dentist(模拟、细节)
- 关于 Android 异步消息处理机制 Handler
- CCTF部分赛题分析
- Leetcode 刷题:Q58 Length of last word
- Ruby入门之一(Ruby简介)
- OJ系列
- spring的bean的作用域