首页 > 其他 > 详细

[Typescript] Introduction to Generics in Typescript

时间:2016-04-29 07:05:22      阅读:277      评论:0      收藏:0      [点我收藏+]

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<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.

[Typescript] Introduction to Generics in Typescript

原文:http://www.cnblogs.com/Answer1215/p/5444970.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!