Default property value in React component using TypeScript

I can’t figure out how to set default property values for my components using Typescript.

This is the source code:

class PageState
{
}

export class PageProps
{
    foo: string = "bar";
}

export class PageComponent extends React.Component<PageProps, PageState>
{
    public render(): JSX.Element
    {
        return (
            <span>Hello, world</span>
        );
    }
}

And when I try to use the component like this:

ReactDOM.render(<PageComponent />, document.getElementById("page"));

I get an error saying property foo is missing. I want to use the default value. I’ve also tried to use static defaultProps = ... inside the component, but it had no effect as I suspected.

src/typescript/main.tsx(8,17): error TS2324: Property 'foo' is missing in type 'IntrinsicAttributes & IntrinsicClassAttributes<PageComponent> & PageProps & { children?: ReactEle...'.

How can I use default property values? Many JS components my company uses rely on them and not using them is not a choice.

11 Answers
11

Leave a Comment