Home > Software engineering >  How to access a conditionally added property in Typescript
How to access a conditionally added property in Typescript

Time:11-03

My React Component Loader get some props.

Property contentAlign exists only when property local exists and local === 'relative';

I can’t put contentAlign in props as I get an error and I can’t access contentAlign in the component (style on <div>) because I don’t accept it in props

How do I access contentAlign?

export type LoaderProps = {
  className?: string;
  background?: string;
  size?: number;
} & (
    | {
        local?: Nullable<boolean>;
      }
    | {
        local: 'relative';
        contentAlign: LoaderContentAlign;
      }
  );

const Loader: React.FC<LoaderProps> = ({
  className,
  background = 'blue',
  local = false,
  size = 30,
  ...props
}: LoaderProps) => {
  console.log('props ', props);
  
  return (
    <div
        className={{local === 'relative' && `loader_content-${props.contentAlign}}}`
    >
      Content
    </div>
  );
};

CodePudding user response:

Typescript doesn't apply smart casting when you use the destructuring assignment. Try this:

const Loader: React.FC<LoaderProps> = ({
  className,
  background = 'blue',
  size = 30,
  ...props
}: LoaderProps) => {
  console.log('props ', props);
  
  return (
    <div
        className={{props.local === 'relative' && `loader_content-${props.contentAlign}}}`
    >
      Content
    </div>
  );
};

CodePudding user response:

Just use the in operator:

"contentAlign" in props && `loader_content-${props.contentAlign}`

Try it.

  • Related