Last active
November 30, 2023 07:47
-
-
Save AshishKapoor/2723f0afaa5fd9a9f7ea795fb39df42f to your computer and use it in GitHub Desktop.
Some examples to understand typescript generics once and for all
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
// Example 1 Generic Function | |
function convertToArrayLegacy<T>(value: T): T[] { // | |
return [value] | |
} | |
const convertToArray = <T extends unknown>(value: T): T[] => { | |
return [value] | |
} | |
console.log(convertToArrayLegacy(12)) | |
console.log(convertToArray("twelve")) | |
// Example 2 Generic function is all about relations | |
function getIndexOfArrayItemLegacy<T>(array: T[], arrayItem: T) { | |
return array.findIndex((item) => item === arrayItem) | |
}; | |
const getIndexOfArrayItem = <T extends unknown>(array: T[], arrayItem: T) => { | |
return array.findIndex((item) => item === arrayItem) | |
}; | |
// OR Shorthand | |
const getIndexOfArrayItemShort = <T,>(array: T[], arrayItem: T) => { | |
return array.findIndex((item) => item === arrayItem) | |
}; | |
const arr = [12,21,33]; | |
const arrStr = ["twelve","twenty-one","thirty-three"]; | |
console.log(getIndexOfArrayItemLegacy(arr, 33)) | |
console.log(getIndexOfArrayItem(arrStr, 'twenty-one')) | |
console.log(getIndexOfArrayItemShort(arrStr, 'twenty-one')) | |
// Example 3 Using multiple generics | |
function createArrayPair<T, U>(input1: T, input2: U): [T, U] { | |
return [input1, input2] | |
} | |
console.log(createArrayPair("Hello", 22)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment