简体   繁体   English

在 Typescript 中创建泛型类型

[英]Creating a Generic Type in Typescript

I had a problem with generic types.我遇到了泛型类型的问题。 I have a user defined type(interface) like this:我有一个像这样的用户定义类型(接口):

IList1: {  
          prop1: string,  
          prop2: number,  
          prop3: string  
          .  
          .  
          . 
       }

IList2:...
IList3:...

and after some serverside response, I get response in the type of Array<Array<,IListx>> .在一些服务器端响应之后,我得到了Array<Array<,IListx>>类型的响应。 So I tried to create a function like this:所以我尝试像这样创建一个 function :

function fun<T>(args:T):Array<Array<T>> {
  return Array<Array<typeof args>>;
}

and variables like this:和这样的变量:

let a:fun<IList1> = ...;
let b:fun<IList2> = ...;
let x:fun<IListx> = ...;

This didn't work.这没有用。 Also I'm not sure this is the correct way of creating a generic type.另外我不确定这是创建泛型类型的正确方法。 I know I did something wrong but couldn't find the proper solution.我知道我做错了什么,但找不到合适的解决方案。 Any help would be appreciated.任何帮助,将不胜感激。

After some trials, I think I found a way by both defining and initializing:经过一些试验,我想我通过定义和初始化找到了一种方法:

function fun<T>():Array<Array<T>> {
  return Array<Array<T>>();
}


let a= fun<IList1>();
let b= fun<IList2>();

worked as expected.按预期工作。 I don't know if there are possible better solutions.我不知道是否有更好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM