web icon indicating copy to clipboard operation
web copied to clipboard

Check Typescript guide for React Flow 12

Open moklick opened this issue 1 year ago • 1 comments

There are a lot of changes regarding types for nodes and edges in React Flow 12. We have a new guide that explains everything but we should double check if it's correct and if it all works. It would be nice if we could add a section about how to type useStore correctly on user side.

moklick avatar Jun 16 '24 09:06 moklick

I've just done a migration from v11 to v12, and I had some head-scratching with the Types for NodeProps.

v11

Before the update, I might have a node component defined like this:


export function BaseEditableNode<T extends HasNumberId>({
  data,
  isConnectable,
  xPos,
  yPos,
  type,
  children,
  className,
  style
}: NodeProps<T> & Pick<GenericDivProps, 'children' | 'className' | 'style'>) {
  

Which gave me correct typing of the data prop when I then wrapped this component in a more specific use case. However, this did not translate at all to v12.

v12

The path of least refactoring ended up being this:


export function BaseEditableNode<
  NodeData extends NodeDataType,
  NodeType extends string,
  BaseNodeType extends NodeBase<NodeData, NodeType>
>({
  data,
  isConnectable,
  positionAbsoluteX,
  positionAbsoluteY,
  type,
  children,
  className,
  style
}: NodeProps<BaseNodeType> &
  Pick<GenericDivProps, 'children' | 'className' | 'style'>) {

Where I had to cut&paste the source code for NodeBase from the xyflow github, and add it to my own codebase. Fortunately, Typescript falls back to duck typing, and this is a working solution that compiler/linter are happy with. However, I would naturally prefer not to have to expose aspects of a libraries internals that aren't intentionally part of its API.

  1. Is there a simpler solution I could have applied?
  2. If not, could the NodeBase be added to the exposed API?
  3. Or if not, could the Type definitions be revised to better infer generic data types?

buchananwill avatar Jul 24 '24 15:07 buchananwill