打字稿中的工厂函数语法

Factory function syntax in typescript

本文关键字:工厂 函数 语法      更新时间:2023-09-26

我不明白这里的c类型标记语法:https://visualstudiomagazine.com/blogs/tool-tracker/2015/12/factory-functions-typescript.aspx

function CreateCustomer<c extends ICustomer>(cust:{new(): c;}, 
                                         name: string, age: number): c

有人可以在 3 个不同的地方解释上面的 c 是什么吗?

1st c 是集合变量必须扩展 ICustomer 的声明(在应用程序中,您可以拥有 VIPCustomer、MegaCustomer...(

那么 2nd c 只是安全防护,c 的构造函数是 100% 扩展 ICustomer(将此对象返回到 cust(

最后一个 c 是整个函数的返回类型。

有好的一天!

  1. <c extends ICustomer>的意思是"c是一种扩展ICustomer的类型">
  2. cust:{new(): c;}的意思是" cust是一个可以用new cust()调用的函数,并将返回一个类型为c的对象">
  3. function CreateCustomer/*...*/(/*...*/): c表示"函数CreateCustomer返回类型为 c 的对象">

该函数可以像这样调用:

var john:Customer = CreateCustomer(Customer, "John", 35)其中Customer是扩展ICustomer接口的类。