Search code examples
reactjstypescriptreact-tsx

define optional props based on other props for react component


I have a component that has a loading state and I have isLoading prop that determines that component is loading or not:

    interface CustomImageComponentProps {
    isLoading:boolean
    src:string
    description:string
}

export const MyCustomImage = ({isLoading}:CustomImageComponentProps) => {

   
    return (
        <If condition={isLoading} OnTrue={
            <Shimmer/>
        } OnFalse={//other content}/>

    );
});

Basically, I want to make other props optional if isLoading is true. How can I achive this behavior using typescript?


Solution

  • thanks for answers but i was able to do this using only typescript and using infer keyword

       type PropType<T extends { isLoading: boolean }> = T extends {isLoading:true }
              ? { src: string , description:string }
              :T extends {isLoading:false}? {}:never;
        
         export const MyCustomImage =<T extends boolean>(
              props: { isLoading?: T } & PropType<T extends infer C ? { isLoading: C } 
                : never>
                ) => {
                   
                    return (
                        <If condition={isLoading} OnTrue={
                            <Shimmer/>
                        } OnFalse={//other content}/>
                
                    );
                });