叫我诺亚。
// AnimalsBase: a package installed via 'npm install animals-base'
export default abstract class Animal {...}
这个抽象基类Animal
在npm
包中定义,可以被其他包扩展:
// earth - I know about it because of 'npm install animals-earth'
import Animal from 'creatures-base'
export class Human extends Animal {...}
export class Cat extends Animal {...}
export class Dog extends Animal {...}
...
您可能知道,我需要在运行时 收集包含各种动物类型的集合。事情是,我永远不确定我将在任何一天工作的星球:
// tatooine - installed via 'npm install animals-tatooine'
import Animal from 'creatures-base'
export class WampRat extends Animal {...}
export class Bantha extends Animal {...}
export class SandPerson extends Animal {...}
...
我甚至可能希望在给定的班次(部署)上工作几个不同的行星......
可以写这个函数吗?
function animalCollection() : [Animal] {
return [ /* An array containing one of each type of animal */ ]
}
如果可能的话,我可以进一步辨别每只动物的家庭行星吗?
function animalCollection(planet) : [Animal] {
return [ /* An array containing one of each type of animal native to 'planet' */ ]
}
答案 0 :(得分:2)
您正在寻找metadata reflection API。
我强烈建议您阅读有关装饰器的事实上的标准文章:Decorators & metadata reflection in TypeScript。
在那里你会发现特别有趣的part #4。