Home > database >  TypeScript how can I make my function generic based on the argument I provide?
TypeScript how can I make my function generic based on the argument I provide?

Time:01-11

I would like to write generic function which accepts generic argument e.g Data<string, number>

here is the code:

interface Data<T,R> {
    a:T;
    c:R;
}

function foo(
  data: Data<string, number>
){
 return test(data)
}

//this func should be generic
function test<?, T extends Data<?, ?>>(
  data: T,
): T {
  return data
}

any ideas?

CodePudding user response:

here you go:

interface Data<T,R> {
    a:T;
    c:R;
}

function foo(
  data: Data<string, number>
){
 return test(data)
}

//this func should be generic
function test<T,R>(
  data: Data<T,R>,
): Data<T,R> {
  return data
}

https://www.typescriptlang.org/play?ts=4.5.4#code/FASwdgLgpgTgZgQwMZQAQBEEQQHgCoA0ASgHyoDewq1qCAXHgNxU1J1HMC wPcArmCQQQAezCo4IkQAoWAEyz0MinAGcIMcAHMCqMHwC2AI1glgASkqoYUCHxjjo66Quzng3HsH6DhY1E4Q LqkstSuSpjYwaQEFnTK0YSkFCxIYqoiADZQAHRZIlouiu7UNnYOqBE8nt5SYRT0AOSBTbpsAEzc5kA

  •  Tags:  
  • Related