TypeScript: Default props not working in functional component

TypeScript Version: 3.4.5

Search Terms: react default props defaultProps functional component stateless

Code

import React from "react";

interface Props {
  name: string;
  optional: string;
}

const Component = ({ name, optional = "default" }: Props) => (
  <p>{name + " " + optional}</p>
);

const Test = () => <Component name="test" />;

Expected behavior: According to the TypeScript 3.0 release notes, the optional prop should not be required in Test as it has been defined with a default using the ES2015 default initializers feature in Component.

Actual behavior: The following compile error is thrown:

Property ‘optional’ is missing in type ‘{ name: string; }’ but required in type ‘Props’.

Playground Link: Link It doesn’t look like the playground supports TSX.

Related Issues: #27425

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 26
  • Comments: 20 (1 by maintainers)

Most upvoted comments

With TypeScript 3.1 or above you should be able to write:

export interface Props {
    name: string;
}

function Greet(props: Props) {
    return <div>Hello {props.name.toUpperCase()}!</div>;
}
Greet.defaultProps = {
  name: "world",
} as Partial<Props>; // Good practice, without it you could use a number as default prop and TypeScript wouldn't complain…

const component = <Greet />; // no errors

The documentation may not be clear on this, but you have to mark the property as optional in your Props interface:

interface Props {
    name: string;
    optional?: string;
}

The purpose of the issue is that the props are not optional, but have a default value (therefore can be eluded when using the component). If you mark the prop optional with ? then TS assumes it could be undefined and forces you to handle that case. However, it will never be undefined because there is a default value. The downvotes are because the commentator did not seem to understand the issue and proposed something that contradicted the 3.0 release notes.

That doesn’t seem to match what the release notes say:

export interface Props {
    name: string;
}

// ...

function Greet({ name = "world" }: Props) {
    return <div>Hello {name.toUpperCase()}!</div>;
}

Any reason why this was closed? Still an issue on 4.1

Although I see everyone referencing work arounds, I am unable to get any of them to work.

I am on version 3.3.3

export interface Props {
  shouldTruncateContent: boolean;
}

const Alert: React.FunctionComponent<Props> = ({
  children,
  shouldTruncateContent = false
}) => {
  return (
        <S.Content shouldTruncateContent={shouldTruncateContent} size="fill">
          {children}
        </S.Content>
  );
};

Alert.defaultProps = {
  shouldTruncateContent: false
} as Pick<Props, 'shouldTruncateContent'>;

export default Alert;

Does anyone have any insight into why this still throws the error

TS2741: Property 'shouldTruncateContent' is missing in type '{ children: string; }' but required in type 'Props'.

I have tried all the fixes proposed in #27425 and #519 too.

You just need to make shouldTruncateContent: boolean; optional shouldTruncateContent?: boolean;

@lakhmeranikita The purpose of this issue is to avoid marking a prop type as optional.

Although I see everyone referencing work arounds, I am unable to get any of them to work.

I am on version 3.3.3

export interface Props {
  shouldTruncateContent: boolean;
}

const Alert: React.FunctionComponent<Props> = ({
  children,
  shouldTruncateContent = false
}) => {
  return (
        <S.Content shouldTruncateContent={shouldTruncateContent} size="fill">
          {children}
        </S.Content>
  );
};

Alert.defaultProps = {
  shouldTruncateContent: false
} as Pick<Props, 'shouldTruncateContent'>;

export default Alert;

Does anyone have any insight into why this still throws the error

TS2741: Property 'shouldTruncateContent' is missing in type '{ children: string; }' but required in type 'Props'.

I have tried all the fixes proposed in #27425 and #519 too.

You can do it in this way, here properties in Props are the optional parameter and further used in the component.

interface Props {
  children: ReactNode;
  properties?: Record<string, unknown>;
}

const defaultProps: Props = {
  children: '',
  properties: {
    marginTop: 32,
    marginLeft: 0,
    marginBottom: 8,
    marginRight: 0,
  },
};

const RadioListLabel: React.FC<Props> = ({
  children,
  properties = defaultProps.properties,
}) => (
  <View
    margin={[
properties ? properties.marginTop : 0
        properties ? properties.marginLeft : 0
        properties ? properties.marginBottom : 0
        properties ? properties.marginRight : 0
      ]}
  >
    <Text size="m" variant="heading2" lineHeight="body">
      {children}
    </Text>
  </View>
  )

Is it a bug that using the default initializer feature does not work for default props? It seems like a regression given that the example given in the release notes does not work on the latest TypeScript version.

@RyanCavanaugh why has the bot closed this issue?

Perhaps I missed it but I do not see an actual answer, despite lot of workarounds?

PS: using TypeScript v4

@the-kenneth what was causing my issue was that I was typing my variable as React.FunctionalComponent.

export interface ButtonProps
  extends React.HtmlHTMLAttributes<HTMLButtonElement> {
  size: ButtonSize;
}

Button.defaultProps = {
  size: ButtonSize.full,
};

const Button: React.FunctionalComponent<ButtonProps> = (props: ButtonProps) => {
  return <StyledButton {...props} />;
};
<Button>bla</Button> => doesn't work. It says it's missing property "size"

Now if I declare button like this:

const Button = (props: ButtonProps) => {
  return <StyledButton {...props} />;
};

it works.

Source: https://github.com/microsoft/TypeScript/issues/27425#issuecomment-478004521

I still think it’s a bug (people explain better in the issue above), but it might be something that works for you

Making the prop optional also means that when you access the props outside of the component (in a test), the type system does not guarantee that the prop exists even though it will always exist.

Example:

const wrapper = shallow(<Test/>);

// optional is string | undefined instead of string
const optional = wrapper
        .find(Component)
        .props()
        .optional;

If optional was a function, you would have to check it exists before you execute it. An example is if you provide a default onClick prop which just calls preventDefault.