zoukankan      html  css  js  c++  java
  • [Typescript] Introduction to Generics in Typescript

    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.

  • 相关阅读:
    web安全之XSS基础-常见编码科普
    Web安全之URL跳转科普
    防止CSRF跨站请求伪造
    Web渗透之mssql LOG备份getshell
    Web渗透之mssql2005 差异备份getshell
    Web渗透之mssql差异备份getshell
    Web安全之url跳转漏洞及bypass总结
    一次对php大马的后门的简单分析
    一些渗透测试基础面试题
    MySQL数据恢复和复制对InnoDB锁机制的影响
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5444970.html
Copyright © 2011-2022 走看看