Issue
Is there a way to nest types and interfaces for better organization?
eg. let myshark: Animals.Fish.Shark
To allow referring the nested Shark
interface, what kind of implementation structure of the interfaces work?
One attempt could be =>
interface Animals{
interface Mamals{
interface Bat {
kind:string;
wings:number;
}
}
interface Fish {
interface Shark {
variant:string;
color:string;
fins:number;
}
}
}
To then use them as follows
let greatwhite: Animals.Fish.Shark;
let mybat: Animals.Mamals.Bat;
I have also tried using classes and namespaces? Is there a proper way to do this or is it not possible to get type declarations such as let myshark: Animals.Fish.Shark
?
Solution
If you don't want to use separate modules for each namespace, you could use TypeScript-specific namespace
s. Either you can define them directly so that Animals
is an actual object at runtime that can hold properties as well as types (and you need to remember to export
anything you want visible from the outside):
namespace Animals {
export namespace Mammals {
export interface Bat {
kind: string;
wings: number;
}
}
export namespace Fish {
export interface Shark {
variant: string;
color: string;
fins: number;
}
}
}
Or you can just declare
the namespace and then anything mentioned within is automatically treated as exported (since otherwise they just wouldn't be declared):
declare namespace Animals {
namespace Mammals {
interface Bat {
kind: string;
wings: number;
}
}
namespace Fish {
interface Shark {
variant: string;
color: string;
fins: number;
}
}
}
Either way you will then be able to refer to the nested interfaces via dot notation, as desired:
let greatwhite: Animals.Fish.Shark; // okay
let mybat: Animals.Mammals.Bat; // okay
Answered By - jcalz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.