如何约束泛型类型具有 new()? [英] How to constraint a generic type to have new()?

查看:26
本文介绍了如何约束泛型类型具有 new()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个类似的功能:

I want to have a function like:

createEntity<TEntity>(): TEntity {
    return new TEntity();
}

在 C# 中,我们可以这样写:

In C#, we could write:

void TEntity CreateEntity<TEntity>() where TEntity : new()

如何在 TypeScript 中执行此操作?

How can I do this in TypeScript?

推荐答案

handbook 做类似的事情是将要初始化的类作为参数发送给工厂方法,并使用 描述它的构造函数新关键字.

The only way shown in the handbook to do something similar to this is to send the class you want to initialize as a parameter to the factory method, and describe it's constructor using the new keyword.

function factory<T>(type: { new (): T }): T {
    return new type();
}

class SomeClass { }

let result = factory(SomeClass);

结果 将是 SomeClass 类型.

The result will be of type SomeClass.

类的构造函数将根据工厂方法中定义的接口进行类型检查.

The constructor of the class will be type checked against the interface defined in the factory method.

如果您想初始化一个在其构造函数中接受参数的类,您必须在提供给工厂方法的接口中指定该参数.

If you want to initialize a class that takes a parameter in it's constructor you will have to specify that in the interface given to the factory method.

function factory<T>(type: { new (...args): T }, ...args): T {
    return new type(...args);
}


class SomeClass {
    constructor(name: string) { }
}

let a = factory(SomeClass, 'John Doe');

这篇关于如何约束泛型类型具有 new()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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