Home > Back-end >  TypeScript function dynamic type inference
TypeScript function dynamic type inference

Time:09-08

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

CodePudding user response:

Use a generic parameter:

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

Playground

  • Related