简体   繁体   中英

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' :

在此处输入图片说明

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM