Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

ts泛型

  • 为什么需要泛型?

    • 因为有些函数结构内容相同,只是某个类型有变化。为了避免重复书写,可以把变化的类型抽象出来(一般用大写字母T表示),调用的时候再用尖括号指定具体类型
  • 使用function定义泛型

    function log<T>(value: T): T {
        return value;
    }
    
    • 用的时候,用尖括号指定
      log < string > "123";
      
    • 也可以使用Ts的类型推断,从参数里自动算出T就是string
      log("123");
      
  • 使用 type 定义泛型

    type Log = <T>(value: T) => T;
    
    const log: Log = (value) => {
        return value;
    }
    
  • 使用interface在内部定义泛型

    interface Log {
        <T>(value: T): T;
    }
    
    const log: Log = (value) => {
        return value;
    }
    
  • 使用interface在外部定义泛型

    interface Log<T> {
        (value: T): T;
    }
    
    const log: Log<string> = (value) => {
        return value;
    }
    
    • 这样整个接口内都能用,但使用接口时必须指定类型(除非像下面在定义时就指定默认类型)
      interface Log<T = string> {
          (value: T): T;
      }
      
  • 使用class在外部定义泛型

    class Person<T> {
        speak(value: T) {
            return value;
        }
    }
    
    • new的时候,用尖括号指定
      let person = new Person<string>();
      
      • 如果不指定,那T就是any