javascripttypescriptdenopreact

Return type for component


I have a forward preact component, but JSR typescript need a component return and what is a button return? The problem is if we use HTMLButtonElement or JSX.Element or JSX.IntrinsicElements["button"] it will not work, any suggestion?


import {
  forwardRef,
} from "preact/compat";
import type { ButtonProps } from "./type.ts";
import { useButton } from "./use-button.ts";
import LoadingSpinner from "../../icon/LoadingSpinner.tsx";
import type { JSX } from "preact/jsx-runtime";
import { UseButtonReturn } from "./index.ts";
const Button = forwardRef<HTMLButtonElement, ButtonProps>((props,ref) => {
  const {
    children,
    className,
    isDisabled,
    GetVariantButton,
    isLoading,
    GetButtonProps,
    GetSpinnerProps,
    GetDisabled,
    endContent,
    startContent,
    GetSlot,
    ...otherProps
  } = useButton({ ...props });
  const LoadSpinner = (
    <LoadingSpinner
      className={`${GetSpinnerProps?.className} ${GetSlot.yuzuSpinner}`}
    />
  );
  return (
    <>
      <button
        {...otherProps}
        className={`flex flex-row items-center justify-center gap-2 ${className} ${GetDisabled} ${GetButtonProps.className} ${GetVariantButton} ${GetSlot.yuzuBase} ${GetSlot.yuzuDisabled}`
          .trim()}
        disabled={isDisabled}
        ref={ref}
      >
        {startContent ? startContent : null}
        {children}
        {endContent ? endContent : null}
        {isLoading ? LoadSpinner : null}
      </button>
    </>
  );
});

export default Button;

//We can't do this

const Button = forwardRef<HTMLButtonElement, ButtonProps>((props,ref): JSX.Element || JSX.IntrinsicElements["button"]  => {} 

For the error console

Checking for slow types in the public API...
error[missing-explicit-type]: missing explicit type in the public API
   | 
61 | const Button= forwardRef<HTMLButtonElement, ButtonProps>((props,ref) => {
   |       ^^^^^^ this symbol is missing an explicit type
   | 
   = hint: add an explicit type annotation to the symbol

  info: all symbols in the public API must have an explicit type
  docs: https://jsr.io/go/slow-type-missing-explicit-type


Solution

  • forwardRef from preact/compat returns this type: preact.FunctionalComponent<PropsWithoutRef<P> & { ref?: preact.Ref<R> }>. As such, a correct annotation would look like this, given your example:

    import type { FunctionalComponent } from 'preact'
    import type { PropsWithoutRef, Ref } from 'preact/compat';
    
    const Button: FunctionalComponent<
      PropsWithoutRef<ButtonProps> & { ref?: Ref<HTMLButtonElement> }
    > = forwardRef<HTMLButtonElement, ButtonProps>((props, ref) => (
      // ...
    ));