【问题标题】:conditional props to react typescript component反应打字稿组件的条件道具
【发布时间】:2020-07-31 23:11:41
【问题描述】:

我正在构建一个采用结构和值参数的反应组件

interface OptionFieldProps {
    structure: { name: string; multi: boolean };
    value: string | string[] | undefined;
}

如果 multi 为真,则值为 string[] | undefined 类型,如果其假值为 string | undefined 类型。我尝试使用泛型来显示这种关系...

type FieldValue <T extends { name: string; multi: boolean }> = 
    T extends { multi: true } ? string[] | undefined : string | undefined

interface OptionFieldProps <T extends { name: string; multi: boolean }> {
    structure: T;
    value: FieldValue<T>;
}

但是当我将它传递给组件时,它说值的类型始终是string | undefined

class OptionField extends Component<OptionFieldProps<{ name: string; multi: boolean }>>{
    render(){
        const { structure, value } = this.props
        //value: string | undefined
    }
}

我应该怎么写才能让打字稿理解这种关系?

【问题讨论】:

    标签: reactjs typescript typescript-generics tsx


    【解决方案1】:

    您应该能够使用联合类型的道具来实现它,其中 single 具有特定类型,multi 具有特定类型。

    例子:

    interface SingleProps {
      structure: { name: string; multi: false };
      value?: string;
    }
    
    interface MultiProps {
      structure: { name: string; multi: true };
      value?: string[];
    }
    
    type MyProps = SingleProps | MultiProps;
    
    const MyComponent = (props: MyProps) => {
      const { value } = props; // string | string[] | undefined
      return <div>...</div>;
    }
    

    【讨论】:

    • 这很好用,直到我不得不做类似 {structure.multi ?
      ...
      :
      ...
      } 知道如何解决这个问题吗?
    • 这应该可行......你到底想在那里做什么,有什么问题?
    猜你喜欢
    • 1970-01-01
    • 2021-04-20
    • 2020-04-08
    • 2021-04-30
    • 1970-01-01
    • 2020-07-26
    • 2021-06-20
    • 2020-08-17
    • 2019-05-22
    相关资源
    最近更新 更多