1

Why does the following doing the following:

type Props = {
  name?: string
  age: number
}

const Test = FC<Props> = (props) => {
  return (
    <h1>Hello, {props.name}. You are {props.age} years old.</h1>
  )
}

Test.defaultProps = {
  name: "John"
}

Give off the warning that name could be undefined when strict mode is set to true even though name is defined in defaultProps.

7
  • 1
    Because you're specifying the name can be undefined in Props Commented Dec 20, 2020 at 5:58
  • 1
    if you are sure that you will be passing name then remove ? if not ask me i have a solution Commented Dec 20, 2020 at 5:59
  • @MoshFeu I thought the point of passing the Props inside FC was that you could do that... Commented Dec 20, 2020 at 6:00
  • @GayatriDipali not necessarily. name has a default value. But if you remove the ? it will ask for the name prop every time you use the component, which is invalid, as it has a default property. Commented Dec 20, 2020 at 6:01
  • Nope. it means that name can be undefined, therefor the code should consider it. You can remove the optional mark (?) because you know that name is never undefined. Commented Dec 20, 2020 at 6:18

2 Answers 2

4

Typescript does not check defaultProps for function components. If you want a default value, you should use ES6 default values, as in:

type Props = {
  name?: string
  age: number
}

const Test: FC<Props> = ({ name = "John" }) => {

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

7 Comments

nvm, i see it's for classes
Yep, classes behave differently.
does that mean that the answer here is wrong? stackoverflow.com/a/37282264/10040604
To my knowledge, the section on function components is wrong: defaultProps on a function component does not change the types. Perhaps there's some compiler flag i'm unaware of that would allow it to work.
|
1

What you could do is:

{props.name ? props.name : "Jhon"}

1 Comment

This works, but defeats the whole purpose of using defaultProps in the first place

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.