我使用以下代码在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)