1

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.

3
  • This needs to be used as an example question somewhere. Very well asked. Commented Feb 11, 2020 at 19:18
  • Property 'message' is missing in type '{}' but required in type 'Props'.ts It says you have required props type. Which is why typescript screams for this :) Just change type props like this message?:string. Commented Feb 11, 2020 at 19:18
  • Also, it might be a good idea to add the JavaScript tag. Commented Feb 11, 2020 at 19:18

1 Answer 1

3

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?"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.