close

How to specify (optional) default props with TypeScript for stateless, functional React components?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to specify (optional) default props with TypeScript for stateless, functional React components? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to specify (optional) default props with TypeScript for stateless, functional React components ?

  1. How to specify (optional) default props with TypeScript for stateless, functional React components ?

    to specify (optional) default props with TypeScript for stateless, functional React components However, the problem is that props always exists (even as an empty object when nothing is passed in). There are 2 workaround for this, though.

  2. How to specify (optional) default props with TypeScript for stateless, functional React components ?

    to specify (optional) default props with TypeScript for stateless, functional React components However, the problem is that props always exists (even as an empty object when nothing is passed in). There are 2 workaround for this, though.

Method 1


Here’s how I like to do it:

type TestProps = { foo: Foo } & DefaultProps
type DefaultProps = Partial<typeof defaultProps>
const defaultProps = {
  title: 'Mr',
  name: 'McGee'
}

const Test = (props: Props) => {
  props = {...defaultProps, ...props}
  return (
    <Text>
      {props.title} {props.name}
    </Text>
  )
}

export default Test

Method 2

To me, this doesn’t look like a typescript issue.

DISCLAIMER: I have only tried this with typescript.

However, the problem is that props always exists (even as an empty object when nothing is passed in). There are 2 workaround for this, though.

The first, unfortunately, kills the super clean curly-brace-less syntax you have, but let’s you keep defaultProps around.

interface TestProps {
    title?: string;
    name?: string;
}

const defaultProps: TestProps = {
    title: 'Mr',
    name: 'McGee'
}

const Test = (passedIn: TestProps) => {
    const props = Object.assign({}, defaultProps, passedIn);
    return (
        <p>
            {props.title} {props.name}
        </p>
    );
}

another alternative that might get a little hairy if you have a TON of props, but that lets you keep your original syntax is something like this:

const Test = (props: TestProps) => (
    <Text>
        {props.title || 'Mr'} {props.name || 'McGee'}
    </Text>
);

Hope this helps!

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment