在TypeScript中从泛型类型获取构造函数/实例

编程入门 行业动态 更新时间:2024-10-26 02:36:27
本文介绍了在TypeScript中从泛型类型获取构造函数/实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我尝试从泛型类型 T 创建实例,例如,

<$ c (); T { return new T(); $ b $ p $但是既然 T code>只是类型而不是构造函数,我们不能这样做。

无法在TypeScript中从泛型创建实例?

我也阅读过这些文章,但找不到解决方案。

  • TypeScript#2037 li>
  • 如何在typescript中的泛型类中的type参数中创建一个新对象?
  • 如何创建我的Typescript类的泛型类型的新实例?

解决方案

如果在调用 new T()时,关于 T 的信息不可用$ c $。

这就是为什么所有替代解决方案都依赖于传递的构造函数,比如这个动态创建类的例子:

interface ParameterlessConstructor< T> { new():T; class ExampleOne { hi(){ alert('Hi'); } } class Creator< T> {构造函数(private ctor:ParameterlessConstructor< T>){ } getNew(){ return new this.ctor(); } } var creator = new Creator(ExampleOne); var example = creator.getNew(); example.hi();

I am trying to create instance from generic type T for example,

class Factory { public static generate<T>(): T { return new T(); } }

But since T is just a type not constructor, we can't do that.

Is it impossible to create an instance from a generic type in TypeScript?

I'v also read these articles but could not found a solution.

  • TypeScript #2037
  • How to create a new object from type parameter in generic class in typescript?
  • How can I create a new instance of the generic type of my Typescript class?

解决方案

The type information used in TypeScript is erased before runtime, so the information about T is not available when you make the call to new T().

That's why all of the alternate solutions depend upon the constructor being passed, such as with this example of creating a class dynamically:

interface ParameterlessConstructor<T> { new (): T; } class ExampleOne { hi() { alert('Hi'); } } class Creator<T> { constructor(private ctor: ParameterlessConstructor<T>) { } getNew() { return new this.ctor(); } } var creator = new Creator(ExampleOne); var example = creator.getNew(); example.hi();

更多推荐

在TypeScript中从泛型类型获取构造函数/实例

本文发布于:2023-11-02 15:08:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552724.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   实例   类型   TypeScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!