• [ts]泛型


    类型变量,一个组件可以支持多种数据类型的数据

    基础用法

    function identity<T>(arg: T): T {
      return arg;
    }
    const output = identity('myString');
    console.log(output);

    泛型变量

    function identity<T>(arg: T[]): T[] {
      return arg;
    }

    泛型接口

    interface GenericIdentityFn<T> {
      (arg: T): T;
    }
    
    function identity<T>(arg: T): T {
      return arg;
    }
    
    let myIndetity: GenericIdentityFn<number> = identity;

    泛型类

    class GenericNumber<T> {
      zeroValue: T;
      constructor (value: T) {
        this.zeroValue = value;
      }
    }
    
    const myGenericNumer = new GenericNumber<number>(123);
    console.log(myGenericNumer);

    泛型约束

    interface Lengthwise {
      length: number;
    }
    
    function identity<T extends Lengthwise>(arg: T): T {
      console.log(arg.length);
      return arg;
    }

    在泛型中使用类类型

    class BeeKeeper {
      hasMask: boolean;
      constructor () {
        this.hasMask = false;
      }
    }
    
    class ZooKeeper {
      nametag: string;
      constructor () {
        this.nametag = 'tom';
      }
    }
    
    class Animal {
      numLegs: number;
      constructor () {
        this.numLegs = 0;
      }
    }
    
    class Bee extends Animal {
      keeper: BeeKeeper;
      constructor () {
        super();
        this.keeper = new BeeKeeper();
      }
    }
    
    class Lion extends Animal {
      keeper: ZooKeeper;
      constructor () {
        super();
        this.keeper = new ZooKeeper();
      }
    }
    
    function createInstance<A extends Animal>(c: new() => A): A {
      return new c();
    }
    console.log(createInstance(Lion).keeper.nametag);
    console.log(createInstance(Bee).keeper.hasMask);
  • 相关阅读:
    cytoscape-d3-force api
    Python基础编程 模块的引入与定义
    更改Ubuntu内核版本
    Jupyter Notebook默认路径修改
    YJZH 前端部署记录 CentOS+Nginx+Vue
    dotnet core webapi centos 服务自启动
    Linux修改时区
    空间数据实战(1)——MySQL
    记录window.sessionStorage的一个小坑
    ElementUI默认表单项el-form-item间距修改
  • 原文地址:https://www.cnblogs.com/zhoulixue/p/15565908.html
Copyright © 2020-2023  润新知