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?


Solution 1:

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