Skip to content

Instantly share code, notes, and snippets.

@bennycode
Last active May 15, 2022 23:29
Show Gist options
  • Save bennycode/75b9000676e06a157c96935218d68ae7 to your computer and use it in GitHub Desktop.
Save bennycode/75b9000676e06a157c96935218d68ae7 to your computer and use it in GitHub Desktop.
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