Last active
November 14, 2022 14:11
-
-
Save alxpsr/b2f891fe234f0ff44353f8a5ad6e04a1 to your computer and use it in GitHub Desktop.
Typescript Generic with Constraints
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
interface INestable<T> { | |
nestedList?: T[]; | |
} | |
interface Item extends INestable<Item> { | |
id: number; | |
nestedList?: Item[]; | |
} | |
const recursiveStructure: Item[] = [ | |
{ | |
id: 1, | |
nestedList: [ | |
{ | |
id: 11, | |
}, | |
{ | |
id: 22, | |
nestedList: [ | |
{ | |
id: 33, | |
} | |
] | |
} | |
] | |
} | |
]; | |
function forEachDeep<T extends INestable<T>>(array: T[], callback: (item: T) => void): void { | |
array.forEach((elem: T) => { | |
if (elem.nestedList) { | |
forEachDeep(elem.nestedList, callback) | |
} | |
callback(item) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment