Search code examples
javascriptreactjstypescripttypesinterface

Change requiring props if at lease on exist


I've type:

export type ButtonProps = {
    href?: string;
    to?: string;
    link?: React.ElementType;
};

And when i use <Button /> with this type and pass to or href, i want to change link to require prop. Like:

if (href || to) then => link is required

I tried add some generic type:

type RequireAtLeastOne<T, Keys extends keyof T = keyof T> =
    Pick<T, Exclude<keyof T, Keys>> 
    & {
        [K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>>
    }[Keys]

Which i find typescript interface require but it didn't help in my case.


Solution

  • You can use something like this:

    export type ButtonProps = {
        to: string;
        link: string;
    } | {
        href: string;
        link: string;
    } | undefined
    
    
    const props1: ButtonProps = {
      to: "asd", 
      link: "123"
    };
    
    const props2: ButtonProps = {
      href: "asd", 
      link: "123"
    };
    
    // Error
    const props3: ButtonProps = {
      to: "asd", 
    };
    
    // Error
    const props4: ButtonProps = {
      href: "asd", 
    };
    

    playground