0

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

0

1 Answer 1

2

Use a generic parameter:

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

Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.