问题描述
我正在尝试编写一个向其使用者公开内部数据结构的类,该类本身将使用该数据结构.
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.
示例:
class Outer {
static Inner = class {
inInner: number
};
constructor(public inner: Outer.Inner) { }
}
这里的问题是Outer.Inner
无法识别为类型.
The problem here is that Outer.Inner
is not recognized as a type.
我找到的唯一答案是解决方法(在Typescript游乐场中).我想知道是否有任何优雅的方法可以做到这一点.
The only answers that I've found are workarounds (in Typescript playground). I'm wondering if there are any elegant ways of doing this.
我有一堆通过客户端和服务器之间的WebSocket发送的动作.每个Action
都有其自己的Data
内部类. Data
类本身在服务器上的其他位置使用.我可以将其分为两个类(或接口),例如Action1
,Action1Data
,但是我认为Action1.Data
是更易读的设计.
I have a bunch of Actions that are sent over WebSockets between client and server. Each Action
has its own Data
inner class. The Data
class itself is used elsewhere on the server. I could separate this into two classes (or an interface), like Action1
, Action1Data
, but I think that Action1.Data
is a more readable design.
推荐答案
您的第二个解决方法"是首选的方式:
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);
TypeScript中有三种声明类型:名称空间,类型和值.您可以使用namespace
来组织类型和值.
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
这不会降低可读性,因为没有内部类"的概念.在TypeScript中.
It does not reduce readability because there is no concept of an "Inner Class" in TypeScript.
请记住,class
语法只是es5原型继承的糖.您将如何在原型继承中表示内部类?您是否将is作为实例变量?或在Outer.prototype.???
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.???
它最终在es5中是这样的:
what it ends up in es5 is something like this:
var Outer = function Outer(...) { ... }
Outer.Inner = function Inner() { ... }
如果您查看的话,Outer.Inner
中的Outer
仅用作命名空间",而来保存Inner
类.
If you look at it, the Outer
in Outer.Inner
is only served as a "namespace" to hold the Inner
class.
这篇关于打字稿:使用静态内部类的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!