Skip to content

Type errors involving forwardRef and Ref in the compatibility layer. #4402

@maxbrieiev

Description

@maxbrieiev

Describe the bug

I am having some issue with preact's compatibility layer. I use Deno and Headlessui, but I don't think it is Deno specific.

There are unexpected type errors, when using forwardRef, ForwardedRef and Ref. When doing import { type Ref } from "react", the preact's compatibility layer appears to resolve the type from preact/hooks/src, but possibly it should be resolved from preact/src instead. This seems to cause type errors.

To Reproduce

mkdir deno-preact-test
cd deno-preact-test
deno init

Add the following to deno.json:

  "imports": {
    "@headlessui/react": "https://esm.sh/@headlessui/react@2.0.4?external=react,react-dom,@types/react",
    "preact": "npm:preact@10.22.0",
    "react": "npm:/preact@10.22.0/compat",
    "react-dom": "npm:/preact@10.22.0/compat",
    "@types/react": "npm:/preact@10.22.0/compat"
  },
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "preact"
  }

Create index.tsx file with the following content:

import * as Headless from "@headlessui/react";
import { type ForwardedRef, forwardRef } from "react";

export const MyInput = forwardRef(
  (props, ref: ForwardedRef<HTMLInputElement>) => {
    return (
      <span>
        <Headless.Input ref={ref} {...props} />
      </span>
    );
  },
);

Run deno check index.tsx and observe the output:

error: TS2322 [ERROR]: Type 'ForwardedRef<HTMLInputElement>' is not assignable to type 'Ref<HTMLElement> | undefined'.
  Type 'null' is not assignable to type 'Ref<HTMLElement> | undefined'.
        <Headless.Input ref={ref} {...props} />
                        ~~~
    at file:///Users/max/code/deno-preact-test/index.tsx:8:25

    The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & CleanProps<"input", InputPropsWeControl | "disabled" | "invalid" | "autoFocus"> & OurProps<"input", InputRenderPropArg> & { ...; } & { ...; } & { ...; }'
        ref?: Ref<RefType>;
        ~~~
        at https://esm.sh/v135/@headlessui/react@2.0.4/X-ZS9AdHlwZXMvcmVhY3QscmVhY3QscmVhY3QtZG9t/dist/utils/render.d.ts:62:5

Screenshot

Screenshot 2024-05-30 at 13 06 30

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions