Another way of defining default Props

3
closed
ankitchouhan1020
ankitchouhan1020
Posted 8 months ago

Another way of defining default Props #415

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.

ankitchouhan1020
ankitchouhan1020
Created 8 months ago

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

sw-yx
sw-yx
Created 8 months ago

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