I don't want to allow undefined values to be passed to components

Viewed 89

I am using swr.
The type of data in swr is IAge| undefined.
I don't want to pass undefined to AgeComponent, so I want the type of age to be IAge.
Since undefined is not allowed in AgeComnponent Type 'IAge | undefined' is not assignable to type 'IAge'. Type 'undefined' is not assignable to type 'IAge'.t error

What should I do if I don't want to allow undefined in the age of the AgeComponent props?

import useSWR from 'swr';
import { IAge } from 'domain/age_groups';

export const useAgeGroups = () => {
  const path = `age_groups`;
  const { data, error } = useSWR<IAge>(path);
  return {
    ages: data,
    agesLoading: !error && !data && data === undefined,
    agesError: error,
  };
};

const Index: FunctionComponent = () => {
  const { ages, agesLoading } = useAgeGroups();
  return (
    <>
      <div>
         {agesLoading && <div>loading</div>}
        <AgeComponent age={ages}/>
      </div>
    </>
  );
};

export default Index;
2 Answers

Just used !!

note: !! is not an operator, it's just the ! operator twice

          const Index: FunctionComponent = () => {
          const { ages, agesLoading } = useAgeGroups();
          const defaultAge = 0; 
          return (
            <>
              <div>
                 {agesLoading && <div>loading</div>}
                <AgeComponent age={!!ages ? age : defaultAge}/>
              </div>
            </>
          );
        };
const Index: FunctionComponent = () => {
  const { ages, agesLoading } = useAgeGroups();
  return (
    <>
      <div>
         {agesLoading && <div>loading</div>}
        {ages && <AgeComponent age={ages}/>}
      </div>
    </>
  );
};

export default Index;

This way TS will infer that ages is defined when passing to props

Related