typescript-cheatsheets/react

Another way of defining default Props

ankitchouhan1020 opened this issue · 3 comments

const GreetComponent = ({ name, age, status }: RequiredProps & DefaultProps) => (
  <div>{`Hello, my name is ${name}, ${age}, ${typeof status === string ? status : status[0]}`}</div>
);

const defaultProps = {
  age: 25,
  status: "" // just for example
} as DefaultProps;

GreetComponent.defaultProps = defaultProps;

type RequiredProps = {
  name: string;
}

type DefaultProps = {
 age: number,
 status: string | string[]
}

In some cases, we might want to have multiple types in a default prop. This option gives the flexibility to assign both types.
Also, it checks for defaultProp type validation.

Yes, but here we are defining DefaultProps explicitly. Not an issue, just another way of doing this.

i'll add a small note :) thank you!