zoukankan      html  css  js  c++  java
  • Typescript基本概念2

    1. 声明合并

    ts声明的重名的类或命名空间,会进行合并

    类合并

    interface Box {
        height: number;
         number;
    }
    
    interface Box {
        scale: number;
    }
    
    let box: Box = {height: 5,  6, scale: 10};

    命名空间合并

    namespace Animals {
        export class Zebra { }
    }
    
    namespace Animals {
        export interface Legged { numberOfLegs: number; }
        export class Dog { }
    }
    
    //等同于
    namespace Animals {
        export interface Legged { numberOfLegs: number; }
    
        export class Zebra { }
        export class Dog { }
    }

    2. mixins

    ts的mixins主要是用来实现类的多继承。可以用类来implements多个类,这样只会继承成员,方法不会。

    在子类中将继承的属性和方法声明占位,用原型复制的方式,添加真正的方法。

    // Disposable Mixin
    class Disposable {
        isDisposed: boolean;
        dispose() {
            this.isDisposed = true;
        }
    
    }
    
    // Activatable Mixin
    class Activatable {
        isActive: boolean;
        activate() {
            this.isActive = true;
        }
        deactivate() {
            this.isActive = false;
        }
    }
    
    class SmartObject implements Disposable, Activatable {
        constructor() {
            setInterval(() => console.log(this.isActive + " : " + this.isDisposed), 500);
        }
    
        interact() {
            this.activate();
        }
    
        // Disposable
        isDisposed: boolean = false;
        dispose: () => void;
        // Activatable
        isActive: boolean = false;
        activate: () => void;
        deactivate: () => void;
    }
    applyMixins(SmartObject, [Disposable, Activatable]);
    
    let smartObj = new SmartObject();
    setTimeout(() => smartObj.interact(), 1000);
    
    ////////////////////////////////////////
    // In your runtime library somewhere
    ////////////////////////////////////////
    
    function applyMixins(derivedCtor: any, baseCtors: any[]) {
        baseCtors.forEach(baseCtor => {
            Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
                derivedCtor.prototype[name] = baseCtor.prototype[name];
            });
        });
    }

    3. 三斜线指令

    /// <reference path="..." /> 在文件头部,表明对其他文件的依赖

  • 相关阅读:
    mysql查看所有触发器以及存储过程等操作集合【转】
    Hutool之Http工具类使用
    SpringCloud之Sentinel
    SpringCloud之Gateway
    com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
    [AWS DA Guru] SQS
    [AWS DA Guru] Kinesis
    [AWS DA Guru] SNS & SES
    [Typescript] Prevent Type Widening of Object Literals with TypeScript's const Assertions
    [AWS] Updating Elastic Beans Talks & RDS
  • 原文地址:https://www.cnblogs.com/mengff/p/12936058.html
Copyright © 2011-2022 走看看