Typescript实例化通用对象 [英] Typescript instantiate generic object

查看:1552
本文介绍了Typescript实例化通用对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个问题,并且搜索了几个小时,找不到合适的解决方案。
我想创建一个通用函数,它可以恢复类型和对象,并将对象转换为该特定类型。但我有麻烦实例化泛型类型。我想知道是否有类似的东西在c#Activator.CreateInstance

I have this problem, and search for hours and can't find the right solution for it. I'm trying to create a generic function that revives an type and an object and convert the object to that specific type. but I'm having troubles to instantiate the generic type. I would like to know if there are something like in c# Activator.CreateInstance

handleResult<T>(response: Response):T {
    let jsonResp = response.json();
    let obj = jsonResp as Object;
    let resp: T = Object.CreateInstance(T); //        
    doTheMambo(resp, obj);
    return resp;
}


推荐答案

在编译期间擦除,并且在生成的JavaScript代码中没有它们的踪迹。所以没有什么像c#中的 CreateInstance

In typescript, generic parameters are erased during the compilation and there is no trace of them in generated javascript code. So there's nothing like CreateInstance from c#.

但是,与c#不同,typecript中的类可以在运行时使用就像其他任何对象一样,所以如果你所需要的只是在运行时创建一个类的实例,你可以很容易地做到这一点(注意它只适用于类,而不是一般的任何类型)。

But, again unlike c#, classes in typescript can be used at runtime just like any other objects, so if all you need is to create an instance of a class at runtime you can do that pretty easily (note that it applies only to classes, not to any type in general).

泛型类型参数看起来有点不寻常:它是一种书写为 {new(... args:any [])的字面类型:T}

The syntax for generic class type argument looks a bit unusual: it's a literal type written as {new(...args: any[]): T}

下面是完整的(它编译)的例子,它和你在你的问题中描述的一样。为了简化,我假设所有需要实例化的对象都必须符合常见的接口结果(否则你必须在doTheMambo中输入一些已知类型来做一些有用的事情)。
$ b $

Here is complete (it compiles) example that does something like you described in your question. For simplification, I supposed that all objects that need to be instantiated must conform to common interface Result (otherwise you have to do type cast to some known type in doTheMambo to do something useful).

interface Response { json(): any }

interface Result { kind: string }

function handleResult<T extends Result>(tClass: { new (...args: any[]): T }, response: Response): T {
    let jsonResp = response.json();
    let obj = jsonResp;
    let resp: T = new tClass();        
    doTheMambo(resp, obj);
    return resp;
}

class Result1 {
    kind = 'result1';
}

function doTheMambo<T extends Result>(response: T, obj: any) {
    console.log(response.kind);
}

const r: Result = handleResult(Result1, { json() { return null } });

这篇关于Typescript实例化通用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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