Generic Functions in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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