Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React/Typescript 2 optional props required together

What is the best practice for having 2 optional props in a component required together with react/typescript.

export interface MyComponentProps {
  firstName?: string;
  lastName?: string;
}
const myComponent: React.FC<MyComponentProps> = (props) => { 
       return <div ...>
     }

my thoughts for requiring both being

export interface Name {
    firstName: string;
    lastName: string;
}
export interface MyComponentProps {
     name?: Name
}

Would this be the best way, or is there another solution out there?

like image 856
Thomas Avatar asked Jul 22 '26 00:07

Thomas


1 Answers

You can use this generic type, which takes a type and makes sure only all of them can exists or none of them can exists.

type AllOrNone<T> = Required<T> | Partial<Record<keyof T, undefined>>;

In your case, usage would be

export interface Name {
    firstName: string;
    lastName: string;
}

export type MyComponentProps = AllOrNone<Name>;

You can try it out in TS Playground

like image 76
Ugur Eren Avatar answered Jul 28 '26 16:07

Ugur Eren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!