Skip to content

Components with generics give type errors with ref in React #2784

@rajsite

Description

@rajsite

🐛 Bug Report

When creating a component with a generic, for example this Dialog that resolves to a string:

const dialogRef = useRef<Dialog<string>>(null);

When used in a ref in jsx:

<NimbleDialog ref={dialogRef}>

You get type errors similar to the following:

Type 'RefObject<Dialog<string>>' is not assignable to type 'LegacyRef<Dialog<void>> | undefined'.
  Type 'RefObject<Dialog<string>>' is not assignable to type 'RefObject<Dialog<void>>'.
    Type 'Dialog<string>' is not assignable to type 'Dialog<void>'.
      Type 'string' is not assignable to type 'void'.

Workaround

The current components that require generics (dialog, drawer, table) export a helper Ref type (DialogRef, DrawerRef, TableRef). That can be used to satisfy the type with a cast:

<NimbleDialog
    ref={dialogRef as unknown as DialogRef}
>

💁 Possible Solution

The root cause and other potential alternatives are discussed here: https://stackoverflow.com/a/58473012
The alternatives discussed are not evaluated and the current workaround and helper types may be a temporary solution.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingtriageNew issue that needs to be reviewed

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions