Interface is such a nice feature in Typescript for custom static type checking. Main reason is to make your code less error prone but I use it primarily for intellisense. Today we will be discussing recursive types.
I need to modal the accordion in HTML using following object.
{
title: "Parent",
expanded: true,
subItems: [
{
title: "Parent",
expanded: true,
subItems:
}]
}
In order to make things easier and not to remember what property each accordion object holds. Let’s use following interface
export interface Accordion{
title: string,
expanded: boolean,
subItems?: Array<{title: string, expanded: boolean, subItems: any}>
}
Look at the subItems as root property, it only covers one level deep accordion. It doesn’t covers a situation when we have multi level deep accordion. In other words an accordion that starts with parent and expand on it’s children and then grand childrens.
That’s where we need recursive types.
All you have to do is to extend the Accordion interface as
export interface Accordion{
title: string,
expanded: boolean,
subItems?: SubAccordion
}
interface SubAccordion extends Array{}