Search code examples
angulartypescripttypesnested

Nested interface definition in Angular


I have an interface with a complex type as a member like this.

export interface Activity {
  id: string;
  name: string;
  segment: Segment;
}

export interface Segment {
  id: string;
  name: string;
}

I'm used to C# and nested classes so somewhere in my spine I feel that this might be improved so that the structure of the segment is inside the activity. I'm not sure what it's called so I failed finding/recognized adequate examples.

Is t even possible in TypeScript/Angular? I'm not sure I've even seen an import to such a nested type ever-ever. In case it's possible, what are the disadvantages/caveats (except the obvious complexity of the interfaces)? In case it's not a feasible choice relying on interfaces, are classes or types something that would be?

Proof of effort.


Solution

  • You can use namespace for that:

    export interface Activity {
      id: string;
      name: string;
      segment: Activity.Segment;
    }
    
    export namespace Activity {
      export interface Segment {
        id: string;
        name: string;
      }
    }