Last active
May 15, 2022 22:40
-
-
Save bennycode/3ef7ad6121a8bbd83d3a9d7c62f84649 to your computer and use it in GitHub Desktop.
Generics 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', 'Sophia', '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); | |
function rollDice(array: any[]): number { | |
return Math.floor(Math.random() * array.length); | |
} | |
function getRandoms<A, B>(array: A[], secondArray: B[]): [A, B] { | |
const a = array[rollDice(array)]; | |
const b = secondArray[rollDice(secondArray)]; | |
return [a, b]; | |
} | |
const [someName, someNumber] = getRandoms<string, number>(names, numbers); | |
console.log(someName, someNumber); | |
interface HttpResponse<T> { | |
code: number; | |
data: T; | |
} | |
interface ResponseData { | |
completed: boolean; | |
id: number; | |
title: string; | |
userId: number; | |
} | |
async function getJson<T>(url: string): Promise<HttpResponse<T>> { | |
const response = await fetch(url); | |
const data: T = await response.json(); | |
return { | |
code: response.status, | |
data, | |
}; | |
} | |
(async () => { | |
const response = await getJson<ResponseData>('https://jsonplaceholder.typicode.com/todos/1'); | |
console.log(response.code, response.data.title); | |
})(); | |
interface User { | |
name: string; | |
} | |
interface Person extends User { | |
shout: () => void; | |
} | |
interface Dog extends User { | |
bark: () => void; | |
} | |
function printName<T extends User>(someone: T): T { | |
console.log(someone.name); | |
return someone; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment