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

时间:2019-05-31 11:24:22

标签: 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[]

1 个答案:

答案 0 :(得分:3)

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);
}