1

I am writing react application with typescript. To provide a typed props I am using the code below.

type ScheduleBoxContentProps = {
  desc: ReactNode,
  lottie: LottieProps,
} & Partial<{className: string}>;

As you can see, I want className prop to be optional, but don't want to define defaultProps for it. In addition, desc and lottie props should be provided.

Is there any better way to define optional without default ?

Edit

I am sorry for the missing context.

If I use React.FC with my custom prop type then there is no problem. Because React.FC uses Partial inside of it.

type MyProps = {
  className?: string;
}
// no erros and warnings
const Component: React.FC<MyProps> = (props) => <div />;

But I don't want my component to accept the children props. I want my component to alert when children props are coming. Thus I am using function components with code below.

// error: default value for className is not provided. 
const Component = ({className}: MyProps) => <div className={className} />;

and it tells me that className's default value are defined. I should define it explicitly. Using code below.

Component.defaultProps = {className: ''};

IMO, it seems little bit unnecessary code, so I decided to use Partial on optional props.

type MyProps = Partial<{className: string}>;

Is there any better way to achieve this? Or, using defaultProps is the best practice?

2 Answers 2

2

You can just add ? after the property name:

type ScheduleBoxContentProps = {
  desc: ReactNode,
  lottie: LottieProps,
  
  // This ? is literally what Partial does
  className?: string,
};

As for your edited example, what I think would be the most simple is to set the default value in the destructuring syntax:

const Component = ({className = ''}: MyProps) => <div className={className} />;
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry for missing context. I added some more information about my situation.
I edited my response with a possible solution
I was thinking too complicated. You point me out the right solution with a basic :) Thanks a lot!. I would use your solution for simple props and Partial for other complicated props if it happens.
1

What about

className?: string;

1 Comment

Sorry for missing context. I added some more information about my situation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.