[英]Angular/typescript tree with child/parent references - how to avoid Block-scoped variable used before its declaration
Lets have a tree of very simple nodes/objects with parents and children references, where we need to reference both, the parent and the children nodes.让我们有一个非常简单的节点/对象树,带有父节点和子节点引用,我们需要在其中引用父节点和子节点。 The tricky part here is that we do want to design and use the nodes not only in the tree but also independently from the tree/ separately.
这里棘手的部分是,我们确实希望不仅在树中设计和使用节点,而且还要独立于树/单独地设计和使用节点。 Meaning, we cannot nest them into the parent nodes directly, but by reference and also reference the child nodes in the parent nodes.
意思是,我们不能直接将它们嵌套到父节点中,而是通过引用并引用父节点中的子节点。 That presents a problem of Typescript error:
这提出了 Typescript 错误的问题:
2448 Block-scoped variable 'rootNode' used before its declaration.ts(2448) 2448块范围变量“rootNode”在其声明之前使用。 ts(2448)
If we place the nodes in descending order we can reference the children above.如果我们按降序放置节点,我们可以引用上面的子节点。 But not the parents below.
但不是下面的父母。 And vice-versa.
反之亦然。 If we place parents above children, we cannot reference the children as they are declared after them.
如果我们把父母放在孩子之上,我们不能引用孩子,因为他们是在他们之后声明的。
It appears that Typescript is not sophisticated enough to pre-compile declarations and throws errors instead.似乎 Typescript 不够复杂,无法预编译声明并引发错误。
How can this be solved?如何解决这个问题?
Here is an example of the tree nodes (placed in descending order) and its ' independent ' nodes with references:这是树节点(按降序排列)及其带有引用的“独立”节点的示例:
export interface Node {
id: string,
value?: string,
parent?: Node,
children?: Node[]
}
export const nodeB2: Node = {
id: 'B2',
value: 'bbb-2',
parent: nodeA1 // ERR 2448
}
export const nodeB1: Node = {
id: 'B1',
value: 'bbb-1',
parent: nodeA1 // ERR 2448
}
export const nodeA1: Node = {
id: 'A1',
value: 'aaa-1',
parent: rootNode, // ERR 2448
children: [nodeB1, nodeB2]
}
export const rootNode: Node = {
id: 'ROOT',
value: 'root',
children: [nodeA1]
}
Give this a try:试试这个:
declare let rootNode: Node;
export interface Node {
id: string,
value ? : string,
parent ? : Node,
children ? : Node[]
}
export const nodeB2: Node = {
id: 'B2',
value: 'bbb-2',
parent: rootNode // ERR 2448
}
export const nodeB1: Node = {
id: 'B1',
value: 'bbb-1',
parent: rootNode // ERR 2448
}
export const nodeA1: Node = {
id: 'A1',
value: 'aaa-1',
parent: rootNode, // ERR 2448
children: [nodeB1, nodeB2]
}
rootNode = {
id: 'ROOT',
value: 'root',
children: [nodeA1]
};
export default rootNode;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.