首页 > 解决方案 > Typescript 创建描述类型类型的属性,该类型基于抽象类型

问题描述

我试图找出泛型并做一个特殊的情况,我根据另一种类型存储一个类型,然后在运行时创建它。

我做了一个糟糕的方法,但我知道必须有更好的方法。

我想要的是:

abstract class AFruit{
   isBad:boolean;
}

class Apple extends AFruit {}
class Orange extends AFruit {}

//problem
interface Storage
{
   fruit: type-base-of-abstract-fruit; //this is what I'd like to figure out
}

//my version
interface Storage
{
   fruit: typeof Apple | typeof Orange;
}


//finally, my example usage:
{fruit: Apple}
//or
{fruit: Orange}

我确实想稍后更新它以使用 Apple 或 Orange,但我还没有弄清楚 typescript 泛型方式。

标签: typescript

解决方案


如果您的意图最终是通过构造一个实例new并且不传入任何参数,那么您希望Storage' 的fruit属性具有可更新的签名,如下所示:

interface Storage {
    fruit: new () => AFruit
}

这将适用于您的示例用法:

const a: Storage = { fruit: Apple }; // okay
const o: Storage = { fruit: Orange }; // okay

如果您尝试分配在没有参数的AFruit情况下调用时不构造实例的东西,它将无法工作。new这打破了:

const oops: Storage = { fruit: AFruit }; // error, abstract

因为AFruitabstract并且没有暴露的新签名。这打破了:

class Tomato extends AFruit {
    constructor(public isItReallyAFruit: boolean) {
        super();
    }
}
const stillOops: Storage = { fruit: Tomato }; // error, bad ctor args

因为是一个类构造函数,当用(例如, )调用时Tomato需要一个boolean参数。newnew Tomato(true);


好的,希望有帮助;祝你好运!

Playground 代码链接


推荐阅读