Typescript: Using the type of a static inner class

前端 未结 2 1979
礼貌的吻别
礼貌的吻别 2021-02-15 01:20

I\'m trying to write a class that exposes an inner data structure to its consumers, a data structure that the class itself will be using.

Example:

class Ou         


        
2条回答
  •  独厮守ぢ
    2021-02-15 02:19

    I found a better workaround for this, that even allows the inner class to access the private members of the outer class, like you would expect in a C#-like language. You can actually easily get the type of the static property with the typeof operator. This small modification to your example works:

    class Outer
    {
        static Inner = class
        {
            inInner: number = 0;
        };
    
        constructor(public inner: typeof Outer.Inner.prototype) { }
    }
    

    But referring to the type as typeof Outer.Inner.prototype gets cumbersome really quickly, so add in this underneath and you can simply refer to it as Outer.Inner as you'd like:

    namespace Outer
    {
        export type Inner = typeof Outer.Inner.prototype;
    }
    

    Combine this with another workaround to allow us to put decorators on the class by making it not an anonymous class and we end up with a fully functional true inner class:

    class Outer
    {
        static Inner = (() =>
        {
            @decoratable()
            class OuterInner
            {
                inInner: number = 0;
            }
            return OuterInner;
        })();
    
        constructor(public inner: Outer.Inner) { }
    }
    
    namespace Outer
    {
        export type Inner = typeof Outer.Inner.prototype;
    }
    

提交回复
热议问题