Typescript: Using the type of a static inner class

前端 未结 2 1970
礼貌的吻别
礼貌的吻别 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:22

    Your second "workaround" is the prefer way to go:

    class Outer {
        constructor(public inner: Outer.Inner) { }
    }
    
    namespace Outer {
        export class Inner {
            inInner: number
        };
    }
    
    // Spec
    let outer1 = new Outer({ inInner: 3 });
    
    let outerInner = new Outer.Inner();
    let outer2 = new Outer(outerInner);
    

    There are three types of declarations in TypeScript: namespace, type, and value. You could use namespace to organize types and value.

    http://www.typescriptlang.org/docs/handbook/declaration-merging.html

    It does not reduce readability because there is no concept of an "Inner Class" in TypeScript.

    Remember that the class syntax is just sugar of es5 prototypal inheritance. How would you represent an inner class in prototypal inheritance? Do you put is as an instance variable? or under Outer.prototype.???

    what it ends up in es5 is something like this:

    var Outer = function Outer(...) { ... }
    Outer.Inner = function Inner() { ... }
    

    If you look at it, the Outer in Outer.Inner is only served as a "namespace" to hold the Inner class.

提交回复
热议问题