Carl Rippon
Carl Rippon

Reputation: 4673

React function component prop default with TypeScript

I'm having trouble with a React function component and defaulting a required prop.

Here's the component:

type Props = { message: string };
function Greeting({ message = "How are you?" }: Props) {
  return <p>{message}</p>;
}

I should be able to consume it without passing the message prop:

<Greeting />

However, TypeScript raises a type error Property 'message' is missing in type '{}' but required in type 'Props':

enter image description here

Here's the issue in a CodeSandbox: https://codesandbox.io/s/still-microservice-lp7b5?fontsize=14&hidenavigation=1&theme=dark

I wasn't sure whether I am doing something wrong or whether this is a glitch in TypeScript? Any help would be appreciated.

Upvotes: 1

Views: 519

Answers (1)

Samuel Hulla
Samuel Hulla

Reputation: 7089

Your Props type definition has a required argument of message, however you're treating it as an optional argument. This is also referenced in the error message you're getting

  • Property 'message' is missing in type '{}' but required in type 'Props'

  • Understand the error message as - your type Props has a required property of message however, your provided type {}, which is missing it (read {} as no provided properties)


Change the definition to the following way:

type Props = {
   message?: string; //< note the '?' at the end of property
};

Now if the component is returned without a specific message prop, it will default to "How are you?"

Upvotes: 3

Related Questions