2016-09-21 162 views
15

如何声明class类型,以便确保该对象是一般类的构造函数?typecript中的类构造函数类型?

在下面的例子,我想知道我应该给这类型AnimalClass,使其既可以是PenguinLion

class Animal { 
    constructor() { 
     console.log("Animal"); 
    } 
} 

class Penguin extends Animal { 
    constructor() { 
     super(); 
     console.log("Penguin"); 
    } 
} 

class Lion extends Animal { 
    constructor() { 
     super(); 
     console.log("Lion"); 
    } 
} 

class Zoo { 
    AnimalClass: class // AnimalClass could be 'Lion' or 'Penguin' 

    constructor(AnimalClass: class) { 
     this.AnimalClass = AnimalClass 
     let Hector = new AnimalClass(); 
    } 
} 

当然,class类型不工作,它会无论如何,这太笼统了。

回答

22
typescript interfaces reference

解决方案:

interface ClockConstructor { 
    new (hour: number, minute: number): ClockInterface; 
} 
interface ClockInterface { 
    tick(); 
} 

function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface { 
    return new ctor(hour, minute); 
} 

class DigitalClock implements ClockInterface { 
    constructor(h: number, m: number) { } 
    tick() { 
     console.log("beep beep"); 
    } 
} 
class AnalogClock implements ClockInterface { 
    constructor(h: number, m: number) { } 
    tick() { 
     console.log("tick tock"); 
    } 
} 

let digital = createClock(DigitalClock, 12, 17); 
let analog = createClock(AnalogClock, 7, 32); 

所以在前面的例子变成:

interface AnimalConstructor { 
    new(): Animal; 
} 

class Animal { 
    constructor() { 
     console.log("Animal"); 
    } 
} 

class Penguin extends Animal { 
    constructor() { 
     super(); 
     console.log("Penguin"); 
    } 
} 

class Lion extends Animal { 
    constructor() { 
     super(); 
     console.log("Lion"); 
    } 
} 

class Zoo { 
    AnimalClass: AnimalConstructor // AnimalClass can be 'Lion' or 'Penguin' 

    constructor(AnimalClass: AnimalConstructor) { 
     this.AnimalClass = AnimalClass 
     let Hector = new AnimalClass(); 
    } 
} 
+0

我只是想补充一点,这种解决方案并没有为我工作,如果你想使用都不行一个构造函数,它接受非零数量的参数。让我永远弄清楚为什么这个例子可行,但我的代码没有。 我经过几个小时的搜索后发现的东西是使用'AnimalClass:typeof Animal'。这将用于动态加载给定类的子类。 – pixelpax

+0

@pixelpax你可以像这样定义一个非零参数构造函数:'new(... args:any []):Animal' – Sammi

+0

@Sammi,谢谢你,你的解决方案确实有意义。对我来说,使用'typeof Animal'来表示“Animal的任何子类的类型”工作得很好,并且在代码中看起来是描述性的。 – pixelpax