Mykyta
Mykyta

Reputation: 396

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

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?

Upvotes: 0

Views: 41

Answers (1)

Mykyta
Mykyta

Reputation: 396

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

Upvotes: 1

Related Questions