antvis/G6

[Suggestion]: imply possible undefined return value for some Graph.get*() methods in document #6784

Crystal-RainSlide posted onGitHub

Describe the bug / é—®é¢˜ęčæ°

https://github.com/antvis/G6/blob/63f15c53be6607a73a4afb3e02b1d527ca220724/packages/g6/src/runtime/graph.ts#L558

Methods like: public getNodeData(id: ID): NodeData; should be: public getNodeData(id: ID): NodeData | undefined;.

TypeScript can't infer possible undefined in array element accesses (array[i]) like:

https://github.com/antvis/G6/blob/63f15c53be6607a73a4afb3e02b1d527ca220724/packages/g6/src/runtime/graph.ts#L575

An example fix with only getNodeData(). Can be applied to other get*() functions.

 class Graph {
   public getNodeData(): NodeData[];
-  public getNodeData(id: ID): NodeData;
+  public getNodeData(id: ID): NodeData | undefined;
   public getNodeData(ids: ID[]): NodeData[];
-  public getNodeData(id?: ID | ID[]): NodeData | NodeData[] {
+  public getNodeData(id?: ID | ID[]): NodeData | NodeData[] | undefined {
     if (id === undefined) return this.context.model.getNodeData();
     if (Array.isArray(id)) return this.context.model.getNodeData(id);
-    return this.context.model.getNodeData([id])?.[0];
+    return this.context.model.getNodeData([id])?.[0] as NodeData | undefined;
   }
 }

To check array element accesses for undefined type safety, either change them to Array.prototype.at() temporarily, or toggle noUncheckedIndexedAccess (doc, changelog, issue for making it usable).

No response

Steps to Reproduce the Bug or Issue / é‡ēŽ°ę­„éŖ¤

const nodeData = new Graph().getNodeData("non-exist-id");
console.assert(typeof nodeData !== undefined);

Version / ē‰ˆęœ¬

šŸ†• 5.x

OS / ę“ä½œē³»ē»Ÿ

  • macOS
  • Windows
  • Linux
  • Others / 其他

Browser / ęµč§ˆå™Ø

  • Chrome
  • Edge
  • Firefox
  • Safari (Limited support / ęœ‰é™ę”ÆęŒ)
  • IE (Nonsupport / äøę”ÆęŒ)
  • Others / 其他

@Crystal-RainSlide We recommend ensuring that the id passed when calling getNodeData and similar APIs exist. However, will consider providing relevant APIs for existence verification later, such as hasNode.

posted by Aarebecca 2 months ago

Then it would be nice to have that mentioned in the JSDoc, can save some users from undefined if they take a look.

posted by Crystal-RainSlide 2 months ago

@Crystal-RainSlide We will improve the relevant docs.

posted by Aarebecca 2 months ago

:tada: This issue has been resolved and is now available in the 5.0.44 release! :tada:

posted by github-actions[bot] about 2 months ago

Fund this Issue

$0.00
Funded

Pull requests