打字稿中的类构造函数类型? [英] Class constructor type in typescript?

查看:54
本文介绍了打字稿中的类构造函数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何声明类型,以确保该对象是常规类的构造函数?

How can I declare a class type, so that I ensure the object is a constructor of a general class?

在下面的示例中,我想知道应该为 AnimalClass 赋予哪种类型企鹅狮子

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

当然,类型不起作用,而且还是太笼统了。

Of course, the class type does not work, and it would be too general anyway.

推荐答案

我不确定是否最初提出问题时,这可能是在 TypeScript 中实现的,但是我的首选解决方案是使用泛型

I am not sure if this was possible in TypeScript when the question was originally asked, but my preferred solution is with generics:

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

这样,变量企鹅 lion 会推断具体类型企鹅 Lion 甚至在TypeScript智能感知中也是如此。

This way variables penguin and lion infer concrete type Penguin or Lion even in the TypeScript intellisense.

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.

这篇关于打字稿中的类构造函数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆