-
Notifications
You must be signed in to change notification settings - Fork 537
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Loading status checks…
tree: Add schema symbol to TreeNodes to allow NodeKind based narrowin…
…g. (#22222) ## Description See changeset for details. This will be used for things like providing object node specific events with strong typing. This is aimed to provide the functionality attempted in alexvy86#7 to better support node kind specific data in #22043
- Loading branch information
1 parent
425111e
commit 4d3bc87
Showing
21 changed files
with
378 additions
and
107 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
--- | ||
"fluid-framework": minor | ||
"@fluidframework/tree": minor | ||
--- | ||
--- | ||
"section": "tree" | ||
--- | ||
Enable compile time type narrowing based on a TreeNode's NodeKind. | ||
|
||
TreeNode's schema aware APIs implement WithType, which now has a NodeKind parameter that can be used to narrow TreeNodes based on NodeKind. | ||
|
||
Example: | ||
|
||
```typescript | ||
function getKeys(node: TreeNode & WithType<string, NodeKind.Array>): number[]; | ||
function getKeys(node: TreeNode & WithType<string, NodeKind.Map | NodeKind.Object>): string[]; | ||
function getKeys(node: TreeNode): string[] | number[]; | ||
function getKeys(node: TreeNode): string[] | number[] { | ||
const schema = Tree.schema(node); | ||
switch (schema.kind) { | ||
case NodeKind.Array: { | ||
const arrayNode = node as TreeArrayNode; | ||
const keys: number[] = []; | ||
for (let index = 0; index < arrayNode.length; index++) { | ||
keys.push(index); | ||
} | ||
return keys; | ||
} | ||
case NodeKind.Map: | ||
return [...(node as TreeMapNode).keys()]; | ||
case NodeKind.Object: | ||
return Object.keys(node); | ||
default: | ||
throw new Error("Unsupported Kind"); | ||
} | ||
} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.