Javascript 你能在 TypeScript 中创建嵌套类吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32494174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:31:20  来源:igfitidea点击:

Can you create nested classes in TypeScript?

javascripttypescript

提问by basarat

Is there a way to nest classes in TypeScript. E.g. I'd like to use them like:

有没有办法在 TypeScript 中嵌套类。例如,我想像这样使用它们:

var foo = new Foo();
var bar = new Foo.Bar();

回答by basarat

Starting with TypeScript 1.6 we have class expressions (reference).

从 TypeScript 1.6 开始,我们有类表达式(参考)。

This means you can do the following :

这意味着您可以执行以下操作:

class Foo {
    static Bar = class {

    }
}

// works!
var foo = new Foo();
var bar = new Foo.Bar();

回答by bnieland

Here is a more complex use case using class expressions.

这是一个使用类表达式的更复杂的用例。

It allows the inner classto access the privatemembers of the outer class.

它允许内部类访问外部类private成员

class classX { 
    private y: number = 0; 

    public getY(): number { return this.y; }

    public utilities = new class {
        constructor(public superThis: classX) {
        }
        public testSetOuterPrivate(target: number) {
            this.superThis.y = target;
        }
    }(this);    
}

const x1: classX = new classX();
alert(x1.getY());

x1.utilities.testSetOuterPrivate(4);
alert(x1.getY());

codepen

代码笔

回答by Dan Def

I couldn't get this to work with exported classes without receiving a compile error, instead I used namespaces:

我无法在没有收到编译错误的情况下使用导出的类,而是使用了命名空间

namespace MyNamespace {
    export class Foo { }
}

namespace MyNamespace.Foo {
    export class Bar { }
}

回答by danvk

If you're in the context of a type declaration file, you can do this by mixing classes and namespaces:

如果您在类型声明文件的上下文中,则可以通过混合类和命名空间来实现:

// foo.d.ts
declare class Foo {
  constructor();
  fooMethod(): any;
}

declare namespace Foo {
  class Bar {
    constructor();
    barMethod(): any;
  }
}

// ...elsewhere
const foo = new Foo();
const bar = new Foo.Bar();

回答by Aydus-Matthew

This approach worked in a typescript Angular2/Ionic2 environment.

这种方法适用于打字稿 Angular2/Ionic2 环境。

foo.ts

import { Bar} from './bar';

export class Foo {
    id: number;
    bar: Bar;
}

bar.ts

bar.ts

export class Bar {
    id: number;
}

Example class usage:

示例类用法:

foo = new Foo();
foo.bar = new Bar();
foo.bar.id = 1;