Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to infer the return type of a function based on an argument that contains a generic?

Tags:

typescript

I don't want to specify the function type every time I call it as I suppose the type can be inferred from the argument somehow. Is it possible?

Here's my current implementation:

export interface Edge<T> {
  items: {
    value: T;
  }[];
}

export function getValuesFromEdge(edge: Edge<T>): T[] {
  return edge.items.map(item => item.value);
}

And the errors I'm seeing:

Cannot find name T for Edge<T>

Cannot find name T for T[]

like image 280
Ramon Balthazar Avatar asked Jan 27 '26 02:01

Ramon Balthazar


1 Answers

You have to because that's the only way to use a generic type for your parameters, but that doesn't mean you have to type each call.

getValuesFromEdge({ items: [{ value: 'SomeValue' }]});

Would work with

export interface Edge<T> {
  items: {
    value: T;
  }[];
}

export function getValuesFromEdge<T>(edge: Edge<T>): T[] {
  return edge.items.map(item => item.value);
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!