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