How do I use namespaces with TypeScript external modules?

前端 未结 9 1426
陌清茗
陌清茗 2020-11-22 08:59

I have some code:

baseTypes.ts

export namespace Living.Things {
  export class Animal {
    move() { /* ... */ }
  }
  export class          


        
9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 09:48

    Try to organize by folder:

    baseTypes.ts

    export class Animal {
        move() { /* ... */ }
    }
    
    export class Plant {
        photosynthesize() { /* ... */ }
    }
    

    dog.ts

    import b = require('./baseTypes');
    
    export class Dog extends b.Animal {
        woof() { }
    }   
    

    tree.ts

    import b = require('./baseTypes');
    
    class Tree extends b.Plant {
    }
    

    LivingThings.ts

    import dog = require('./dog')
    import tree = require('./tree')
    
    export = {
        dog: dog,
        tree: tree
    }
    

    main.ts

    import LivingThings = require('./LivingThings');
    console.log(LivingThings.Tree)
    console.log(LivingThings.Dog)
    

    The idea is that your module themselves shouldn't care / know they are participating in a namespace, but this exposes your API to the consumer in a compact, sensible way which is agnostic to which type of module system you are using for the project.

提交回复
热议问题