简体   繁体   中英

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>> . So I tried to create a function like this:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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