Bobby Gagnon
Bobby Gagnon

Reputation: 80

TypeScript function dynamic type inference

I have this function:

const randomFromArray = (array: unknown[]) => {
     return array[randomNumberFromRange(0, array.length - 1)];
};

My question is how can I dynamically type this input instead of using unknown or any. When I call this function, it understandably returns a type of unknown but I'd like for it to return the type that it was called with.

i.e. The returned type from randomFromArray(['red', 'blue']), would be string and the returned type from randomFromArray([1, 2]), would be number

Upvotes: 0

Views: 220

Answers (1)

tenshi
tenshi

Reputation: 26324

Use a generic parameter:

const randomFromArray = <T>(array: T[]): T => {
     return array[randomNumberFromRange(0, array.length - 1)];
};

Playground

Upvotes: 2

Related Questions