typescript - Typescript 创建描述类型类型的属性,该类型基于抽象类型
问题描述
我试图找出泛型并做一个特殊的情况,我根据另一种类型存储一个类型,然后在运行时创建它。
- 我已经看到了,我的接口因我的属性而失败: typeof 抽象类和扩展器
- 我也想了解: https ://www.typescriptlang.org/docs/handbook/utility-types.html
我做了一个糟糕的方法,但我知道必须有更好的方法。
我想要的是:
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 泛型方式。
解决方案
如果您的意图最终是通过构造一个实例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
因为AFruit
是abstract
并且没有暴露的新签名。这打破了:
class Tomato extends AFruit {
constructor(public isItReallyAFruit: boolean) {
super();
}
}
const stillOops: Storage = { fruit: Tomato }; // error, bad ctor args
因为是一个类构造函数,当用(例如, )调用时Tomato
需要一个boolean
参数。new
new Tomato(true);
好的,希望有帮助;祝你好运!
推荐阅读
- python - 通过命令提示符运行 python 程序时未找到模块错误
- elasticsearch - 无法使用 weblogic 服务器运行弹性搜索
- android - androidstudio 服务在 Androidx 中不工作
- tcpdump - Tcpdump 基于长度的动态过滤器
- java - 将 java 7 迁移到 java 8 - forEach 中的 forEach 用于 HashMap 中的 HashMap?
- python-3.x - Python格式不完整日期为YYYYMM
- idl-programming-language - 如何通过 IDL 将超过 7 列写入 csv 文件?
- asp.net-mvc - 如何保护没有验证的旧网站?
- ruby - 配置文件,logstash ruby filter event.get("message").match() 错误
- python-3.x - 使用 pickle 加载 TfidfVectorizer 时解决 AttributeError