Utilizing a Nested Interface in an Angular Directive
When working in Java, I have found static nested classes to be a helpful way to structure my code. Now, when trying to do something similar in Typescript with Angular, I'm running into some challenges setting it up properly.
The code snippet below is almost functional, but I'm struggling with whether or not to export the namespace:
If I choose to export the namespace, I encounter an issue when trying to declare the directive within the module that contains it. This results in the following warning:
'MyDirective' is not defined in any Angular module.
However, if I opt not to export the namespace, I face difficulties typing objects as MyDirective.DirectiveOptions
due to the error shown here:
TS2702: 'MyDirective' is only recognized as a type, even though it's being used as a namespace in this context.
The definition of my directive:
@Directive({
selector: '[appMyDirective]'
})
export class MyDirective implements OnInit {
defaultDirectiveOptions: MyDirective.DirectiveOptions = {
callback: () => {console.log('default callback called')}
};
@Input('appMyDirective')
directiveOptions: MyDirective.DirectiveOptions = {};
ngOnInit(): void {
this.directiveOptions = {...this.defaultDirectiveOptions, ...this.directiveOptions};
}
}
// It may seem unconventional, but here is how I nest an interface.
export namespace MyDirective {
export interface DirectiveOptions {
callback?: () => void;
}
}
In another file named foo.component.ts
:
options: MyDirective.DirectiveOptions = {
callback: ()=>{
console.log('Overridden callback called');
}
}