dagda1
dagda1

Reputation: 28770

typescript 3.0 and react defaultProps

If I have a prop defined like this:

interface Props {
  Layout?: LayoutComponent;
}

Then if I supply defaultProps on on a ClassComponent:

class MyComp extends React.Component<Props> {
  static defaultProps: Pick<Props, 'Layout'> = {
    Layout: ({ children }) => <>{children}</>
  };
}

Typescript does not pickup the fact that it cannot be undefined:

render() {
    const { previousLocation, data } = this.state;
    const { location, Layout } = this.props;
    const initialData = this.prefetcherCache[location.pathname] || data;

    return (
      <Layout> // JSX element type 'Layout' does not have any construct or call signatures.
        <Switch>

It should never be undefined because of the defaultProps. Typescript does not pick this up.

Is there anyway of letting the compiler know that it cannot be undefined?

Upvotes: 1

Views: 1527

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37918

TL;DR do not define Layout prop as optional, typescript will handle it on its own.

Internally Layout prop shouldn't be optional as it is always defined due to the defaultProps:

interface Props {
  Layout: LayoutComponent;
}

For external users any prop that has a default prop is transformed to be optional by LibraryManagedAttributes

This helper type defines a transformation on the component's Props type, before using to check a JSX expression targeting it; thus allowing customization like: how conflicts between provided props and inferred props are handled, how inferences are mapped, how optionality is handled, and how inferences from differing places should be combined

Upvotes: 3

Related Questions