Follow up from: Define enum as static property of class
In the following code we have a Box class with a Color enum property defined on it such that the type can be referenced with Box.Color
.
class Box {
constructor(private color: Box.Color) {}
}
namespace Box {
export enum Color {
RED,
GREEN,
BLUE,
}
}
function createBox (color: Box.Color): Box {
return new Box(color);
}
const box = createBox(Box.Color.RED);
console.log(box); // { color: 0 }
My problem is now when I try to subclass Box
the Color
property carries over (in JavaScript) but the type information doesn't carry over in TypeScript.
class SmallBox extends Box { }
function createSmallBox (color: SmallBox.Color): SmallBox {
// ^ Error
return new SmallBox(color);
}
const box = createSmallBox(SmallBox.Color.RED);
// ^ Works
console.log(box);
This works in JavaScript because SmallBox
inherits the static Color
property from Box
. However, it doesn't work in TypeScript because the type information is lost. Is there some way to accomplish the same thing while maintaining the type information? I'm looking for a generic way that will keep all type information from Box and apply it to SmallBox without having to create a new SmallBox
namespace and list every type manually.
Edit: I have been able to come up with the following which requires an extra namespace to pass things around. I would love to get rid of the extra sub-namespace if possible though.
class Box {
constructor(private color: Box.Subtypes.Color) {}
}
namespace Box {
export namespace Subtypes {
export enum Color {
RED,
GREEN,
BLUE,
}
}
}
function createBox (color: Box.Subtypes.Color): Box {
return new Box(color);
}
class SmallBox extends Box { }
namespace SmallBox {
export import Subtypes = Box.Subtypes;
}
function createSmallBox (color: SmallBox.Subtypes.Color): SmallBox {
// ^ Works
return new SmallBox(color);
}
const box = createSmallBox(SmallBox.Subtypes.Color.RED);
// ^ Works
console.log(box);