简体   繁体   English

反应 Typescript 组件与多种道具类型

[英]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.我有以下组件,它将接受一个配置对象,该对象可以是一个包含name属性的对象,该属性将是一个字符串,或者在配置对象尚未填充的情况下是一个布尔值。

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) TS 抱怨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) . Property 'config' does not exist on type 'boolean | { config: Config; }'.ts(2339) What is the correct TS fix?什么是正确的 TS 修复? It seems that annotating it with type any does seem to work, but I'd obviously like to avoid this.似乎用any类型注释它似乎确实有效,但我显然想避免这种情况。

I think you can only solve your problem using null .我认为您只能使用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 .该错误与boolean相关。

In making the parameter { config }: { config: Config } | boolean在制作参数{ config }: { config: Config } | boolean { config }: { config: Config } | boolean , you're saying: { config }: { config: Config } | boolean ,你是说:

  • the parameter may be { config: Config } , or参数可能是{ config: Config } ,或
  • the parameter may be boolean .参数可能是boolean

With a JSX component, the parameter is the props in the form of an object.对于 JSX 组件,参数是对象形式的道具。 In what case will JSX props be boolean?在什么情况下 JSX props 是布尔值? 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):或者如果您希望 config 有时出于某种原因接受true / false (您可能不想这样做):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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