我使用以下代码在TypeScript中使用nested classes:

class Parent {
  private secret = 'this is secret'
  
  static Child = class {
    public readSecret(parent: Parent) {
      return parent.secret
    }
  }
}

这是基于the following answer.它允许我的Child类访问Parent类的私有属性.

我想用嵌套类类型键入一个变量,我很天真地从以下代码开始:

type NestedType = Parent.Child
const child: NestedType = new Parent.Child()

但我得到了以下错误:

'Parent' only refers to a type, but is being used as a namespace here. ts(2702)

我try 使用typeof运算符:

type NestedType = typeof Parent.Child
const child: NestedType = new Parent.Child()

但它不起作用:

Property 'prototype' is missing in type '(Anonymous class)' but required in type 'typeof (Anonymous class)'. ts(2741)

最后我终于成功了:

const nestedTemplate = new Parent.Child()
type NestedType = typeof nestedTemplate
const child: NestedType = new Parent.Child()

然而,这段代码创建了一个无用的Child实例.这是TS语言的限制吗?

仅供参考,我还try 使用名称空间:

class Parent {
  private secret = 'this is secret'
}

namespace Parent {
  export class Child {
    public readSecret(parent: Parent) {
      return parent.secret
    }
  }
}

但是Child类不再能够访问Parent类的私有属性:

Property 'secret' is private and only accessible within class 'Parent'. ts(2341)

推荐答案

使用typeof-child原型应该足以解决打字问题.

class Parent {
  private secret = 'this is secret'

  static Child = class {
    public readSecret(parent: Parent) {
      return parent.secret
    }
  }
}

const child: typeof Parent.Child.prototype = new Parent.Child();
console.log(child.readSecret(new Parent()));

你可以在那里测试Playground Link

这样就不必实例化任何中间类.

Javascript相关问答推荐

使用typeof运算符获取对象值类型-接收字符串而不是数组

如何在NightWatch.js测试中允许浏览器权限?

RxJS setTimeout操作符等效

使用下表中所示的值初始化一个二维数组

网页自检测外部元素无法加载

从WooCommerce Checkout Country字段重新排序国家,保持国家同步

单击ImageListItemBar的IconButton后,在Material—UI对话框中显示图像

为什么Mutations 观察器用微任务队列而不是macrotask队列处理?

用于编辑CSS样式的Java脚本

Reaction Native中的范围滑块

当id匹配时对属性值求和并使用JavaScript返回结果

对网格项目进行垂直排序不起作用

如何在Svelte中从一个codec函数中调用error()?

如何将zoom 变换应用到我的d3力有向图?

处理app.param()中的多个参数

TabNavigator和StackNavigator之间的Reaction Native中的导航问题

在Press Reaction本机和EXPO av上播放单个文件

如何用react组件替换dom元素?

Reaction-在同一页内滚动导航(下拉菜单)

JavaScript -如何跳过某个字符(S)来打乱字符串中的字符