Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generic Functions in TypeScript
function getRandom<T>(array: T[]): T {
const diceRoll = Math.floor(Math.random() * array.length);
return array[diceRoll];
}
const names = [
'Amelia', 'Ava', 'Benjamin', 'Charlotte', 'Elijah', 'Emma',
'Evelyn', 'Harper', 'Henry', 'Isabella', 'James', 'Liam', 'Lucas', 'Mia',
'Noah', 'Oliver', 'Olivia', 'Sofia', 'Theodore', 'William'
];
const randomName = getRandom(names);
console.log(randomName);
const numbers = [159, 321, 330, 37, 471, 500, 614, 672, 727, 861];
const randomNumber = getRandom(numbers);
console.log(randomNumber);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment