wurikiji
wurikiji

Reputation: 327

typescript: Better way to type optional without default value?

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?

Upvotes: 1

Views: 754

Answers (2)

Luiz Ferraz
Luiz Ferraz

Reputation: 1525

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} />;

Upvotes: 2

angelos_lex
angelos_lex

Reputation: 1661

What about

className?: string;

Upvotes: 1

Related Questions