[Typescript] Introduction to generics in Typescript

Source: Internet
Author: User

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

Let's say we have this part of code:

class emitter{    Emit (event) {        console.log (event);    }} Const New  '/home'true});

The object we want to pass on is {path: "", Directory: ""}. But it could happen that we had some typo error, so we want the IDE helps us to detect that.

To does this, we need interface:

 class  emitter<myevent>{emit (  event  : MyEvent) {Console.log ( Span style= "color: #0000ff;"    >event  ); }}  interface   myevent{path:  string   Directory:boolean}  const  emitter = new  emitter<myevent> (); Emitter.emit ({path:   " /home  Span style= "color: #800000;" > ' , directory: true }); 

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

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

classemitter<t>{//T:allow everything come inEmitEvent: MyEvent) {Console.log (Event); }    yield(value:myvalue) {console.log (value); }}Interfacemyevent{Path:stringDirectory:boolean}Interfacemyvalue{Message:string}ConstEmitter =NewEmitter<myevent>();ConstYielder =NewEmitter<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>, and then for each function, we add the interface for th At.

[Typescript] Introduction to generics in Typescript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.