【问题标题】:Typescript create property that describes a type of type, which is based on abstract typeTypescript 创建描述类型类型的属性,该类型基于抽象类型
【发布时间】:2020-06-16 05:52:47
【问题描述】:

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

我的方法很糟糕,但我知道必须有更好的方法。

我想要什么:

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


    【解决方案1】:

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

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

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

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

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

    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 是一个类构造函数,当使用new(例如new Tomato(true);)调用时需要一个boolean 参数。


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

    Playground link to code

    【讨论】:

    • 谢谢你,@jcalz!我花了一段时间才理解,而且我也过度简化了这个例子。我也问你这个。我再次回顾了引用的stackoverflow,他们在其中添加了new (...a: any[]),并在其中传递了参数。我知道这是通用的,但如果参数总是ctor(string, boolean, number),你会怎么写?
    • new (a: string, b: boolean, c: number) => AFruit 我认为会起作用
    • 再次感谢您!我真的比 es6+ 更喜欢 typescript;尤其是因为我之前使用 c# 的经验,但它对我来说仍然是超级新的。再次感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多