类构造函数的类型是什么?

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

In the following example, I want to know which type should I give to AnimalClass so that it could either be Penguin or Lion:

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类型不起作用,而且无论如何它都太一般了。

195653 次浏览

编辑: 这个问题已经在2016年得到了回答,有点过时了。看看下面@Nenad 的最新回答。

来自 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();
}
}

Like that:

class Zoo {
AnimalClass: typeof Animal;


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

Or just:

class Zoo {
constructor(public AnimalClass: typeof Animal ) {
let Hector = new AnimalClass();
}
}

typeof Class is the type of the class constructor. It's preferable to the custom constructor type declaration because it processes static class members properly.

这是 打字脚本文档的相关部分。搜索 typeof。作为 TypeScript 类型注释的一部分,它的意思是“给我一个名为 Animal 的符号类型”,在我们的示例中,这是类构造函数的类型。

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

构造函数类型可定义为:

 type AConstructorTypeOf<T> = new (...args:any[]) => T;


class A { ... }


function factory(Ctor: AConstructorTypeOf<A>){
return new Ctor();
}


const aInstance = factory(A);

当问题最初被问到时,我不确定这在 打字机中是否可行,但我倾向于使用 非专利药:

class Zoo<T extends Animal> {
constructor(public readonly AnimalClass: new () => T) {
}
}

这样变量 penguinlion即使在 TypeScript 智能感知中也能推断出具体的 PenguinLion类型。

const penguinZoo = new Zoo(Penguin);
const penguin = new penguinZoo.AnimalClass(); // `penguin` is of `Penguin` type.


const lionZoo = new Zoo(Lion);
const lion = new lionZoo.AnimalClass(); // `lion` is `Lion` type.