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.

Hansel
  • 1,568
  • 1
  • 15
  • 29
  • 1
    Because you're specifying the `name` can be undefined in `Props` – Mosh Feu Dec 20 '20 at 05:58
  • 1
    if you are sure that you will be passing name then remove `?` if not ask me i have a solution – Gayatri Dipali Dec 20 '20 at 05:59
  • @MoshFeu I thought the point of passing the `Props` inside `FC` was that you could do that... – Hansel Dec 20 '20 at 06: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. – Hansel Dec 20 '20 at 06: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. – Mosh Feu Dec 20 '20 at 06:18
  • @GayatriDipali as I told @MoshFeu that will not work. As it forces you to pass down `name` if you remove the `?` even though it has a default value. – Hansel Dec 20 '20 at 06:23
  • you could just do this `

    Hello, {props?.name}. You are {props?.age} years old.

    `
    – Rogelio Dec 20 '20 at 06:23

2 Answers2

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" }) => {

}
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
1

What you could do is:

{props.name ? props.name : "Jhon"}
Gayatri Dipali
  • 1,171
  • 4
  • 16