简体   繁体   中英

React Typescript Component with Multiple Prop Types

I have the following component where it will take a config object, which can either be an object which contains a name property which will be a string, or a boolean in the case that the config object has not been populated yet.

type Config = {
  name: string;
};

const Widget = ({ config }: { config: Config } | boolean) => {
  return <p>{config.name}</p>;
};

export default function App() {
  let config = {
    name: "Bob"
  };
  // config = false;
  return (
    <div>
      <h1>Name:</h1>
      {config && <Widget config={config} />}
    </div>
  );
}

TS is complaining that Property 'config' does not exist on type 'boolean | { config: Config; }'.ts(2339) Property 'config' does not exist on type 'boolean | { config: Config; }'.ts(2339) Property 'config' does not exist on type 'boolean | { config: Config; }'.ts(2339) . What is the correct TS fix? It seems that annotating it with type any does seem to work, but I'd obviously like to avoid this.

I think you can only solve your problem using null . Your code would look like this:

   type Config = {
        name: string
    }
    
    const Widget = (config : Config | null) => {
    
        if(!config) {
           return !--- not populated config code
        } else {
            <p>{config.name}</p>;
        }
    };

The error is related to the boolean .

In making the parameter { config }: { config: Config } | boolean { config }: { config: Config } | boolean , you're saying:

  • the parameter may be { config: Config } , or
  • the parameter may be boolean .

With a JSX component, the parameter is the props in the form of an object. In what case will JSX props be boolean? Never. So that's likely the error.

Change it to:

const Widget = ({ config }: { config: Config }) => {
  return <p>{config.name}</p>;
};

or if you want config to be optional:

const Widget = ({ config }: { config?: Config }) => {
  return <p>{config.name}</p>;
};

or if you want config to sometimes accept true / false for some reason (you probably don't want to do this):

const Widget = ({ config }: { config: Config | boolean }) => {
  return <p>{config.name}</p>;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM