preact-and-typescript icon indicating copy to clipboard operation
preact-and-typescript copied to clipboard

Type-hinting functional components with JSX attributes?

Open mindplay-dk opened this issue 6 years ago • 3 comments

Thanks for this brilliant source of reference! Really cuts through the noise :-)

What's missing for me, is how to type-hint a functional component that accepts standard JSX attributes?

I tried the following:

import { h, FunctionalComponent } from "preact";

export interface ButtonProps {
    title: string;
}

export const Button: FunctionalComponent<ButtonProps> = props => {
    let { title, ...rest } = props;

    return <button {...rest}>{title}</button>;
};

But I get the following error:

Type '(ButtonProps & ComponentProps<FunctionalComponent<ButtonProps>>) | undefined' has no property 'title' and no string index signature.

Clearly, type-hinting as FunctionalComponent<ButtonProps> isn't the right way to go about this?

mindplay-dk avatar Mar 07 '18 10:03 mindplay-dk

Like this maybe?

import { h } from "preact";

export interface ButtonProps {
    title: string;
}

export const Button = (props: JSX.HTMLAttributes) => {
    const { title, ...rest } = props;

    return <button {...rest}>{title}</button>;
};

mindplay-dk avatar Mar 07 '18 10:03 mindplay-dk

Hmm, no, that doesn't give me access to children 🙄

mindplay-dk avatar Mar 07 '18 10:03 mindplay-dk

Sorry it took me a little while to get around to this, but it looks like developit/preact#1033 may have solved the issue? It's not been released yet, but using the updated definition it appears your examples now work.

scurker avatar Mar 12 '18 20:03 scurker