【问题标题】:Require at least one prop to be passed to component [typescript] [duplicate]需要至少一个道具传递给组件[打字稿] [重复]
【发布时间】:2021-03-02 03:04:35
【问题描述】:

快速提问 - 假设我有一个这样的组件:

interface ComponentInterface {
    nameA: string;
    nameB?: string;
}

const Component: React.FC<ComponentInterface> = (props) => {
     const { nameA, nameB } = props 
     const name = nameB || nameA;

     return <div>Hello World! Name: {name}</div>
}

如果我们不传递 nameA,Typescript 中是否有办法强制 nameB?

写&lt;Component nameA={""} nameB={"John"} /&gt;感觉不好,我不想把nameA变成nameA?: string,因为我至少要传递一个props。

这是一个过于简化的 c 版本。提早提!

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    是的,你可以使用联合类型:

    
    interface Props1 {
        nameA: string;
        nameB?: string;
    }
    
    interface Props2 {
        nameB: string;
    }
    
    type Props = Props1 | Props2
    

    意思是,如果你通过nameA,nameB 是可选的。但是如果你没有通过nameA - nameB 是必需的。

    【讨论】:

      猜你喜欢
      • 2020-07-07
      • 2021-11-10
      • 2021-11-18
      • 1970-01-01
      • 2021-11-07
      • 2021-06-17
      • 2011-07-21
      • 2015-01-14
      相关资源
      最近更新 更多