Typescript任意数量的泛型类型

时间:2019-12-13 18:03:33

标签: typescript

在Typescript中可以创建具有任意数量的泛型类型的类吗?像这样:

class CommonClass<T:any,...R:any[]> { 
    //some stuffs ... constructor, properties....
}

// it's usage...

const myObj = new CommonClass<Obj1,Obj2,Obj3>();
const yourObj = new CommonClass<Obj4,Obj5>();

[编辑] 按照jcalz的评论请求,我将更好地解释为什么它应该有用。

我正在实现使用CQRS模式CQRS - Martin Fowler的API 因此,让我们想象一个简单的应用程序:

目标:客户将下订单,应用程序将通过电子邮件发送订单票证注册。

应用上下文:当订单请求来自客户请求时,控制器必须交付此命令“ PlaceOrder” 我们的命令处理程序 告诉我们的模型下订单。因此,在持久性数据之后的订单模型将发送“ OrderPlaced” 事件,并且所有侦听器都将执行其工作,例如邮件组件,例如,他们已收到有关某些“ OrderPlaced”的通知并将其票证发送给客户。

我打算防止代码重复,例如对于我们的模型,许多模型将完成非常常见的工作。更新| ],但是在某些特殊情况下,某些模型将调度其他事件(此处的事件是将处理其他任务的类)。 CommonModel将是维护单个代码库并仅需更改少量内容的理想类。

让我们看一个实际的例子:

class CommonModel<T:any,..R:any[]> {
    construct() {}

    create(entity:T) {
       //perform save to our database.

       //here dispatch a common related create event
       this.apply(new R[0](someStuff));

    }
}


import { OrderPlacedEvent } from './some_dir/order.placed';
import { Order } from './some_dir/order.entity';
class OrderModel extends CommonModel<Order,OrderPlacedEvent>{}

class CreateOrderCommand {

    constructor() {super();}

    //method called internally
    handle() { 

       const orderModel = new OrderModel();
       orderModel.create(filledEntity);

    }
}

好吧,在上面的代码中OrderModel类扩展了CommonModel,它的用法很简单,没有任何覆盖。

// But in somewhere Mail has interpected OrderPlaced event and
// make it's job

import { MailSentEvent } from './some_dir/mail.sent';
import { MailLogging } from './some_dir/mail.logging';
import { Mail } from './some_dir/mail.entity';

//Pay attention here we have the 3rd type...
class MailModel extends CommonModel<Mail,MailSentEvent,MailLogging>{
    constructor() {super();}

    //override because we also need use our MailLogging...
    create(entity:Mail){
       super.create(entity);

       //here our extra behavior
       const log = new MailLogging();
       log.write('A new mail was sent somewhere in time');
    }
}
// Triggered by some listener 
class SendEmailCommand {

    constructor() {super();}

    //method called internally
    handle() { 

       const mailModel = new MailModel();
       mailModel.create(filledEntity);

    }
}

在一个最小的,显然是非功能的代码示例上,缺少了很多东西 但是很好解释

我希望我很清楚。预先感谢!

1 个答案:

答案 0 :(得分:0)

似乎他们将从Typescript v4.0.0开始添加可变的元组类型:

这不是您(或其他绊脚石)可能想要的确切解决方案,一定会有所帮助。