Skip to content

Instantly share code, notes, and snippets.

@alxpsr
Last active November 14, 2022 14:11
Show Gist options
  • Save alxpsr/b2f891fe234f0ff44353f8a5ad6e04a1 to your computer and use it in GitHub Desktop.
Save alxpsr/b2f891fe234f0ff44353f8a5ad6e04a1 to your computer and use it in GitHub Desktop.
Typescript Generic with Constraints
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