【问题标题】:Deconstructing Props from React Component with Typescript and Union Interface使用 Typescript 和 Union 接口从 React 组件中解构 Props
【发布时间】:2018-06-02 22:56:57
【问题描述】:

我的 Props 接口分为基本接口和两种联合类型:

interface BaseProps {
  ...
}

interface ControlledInput extends BaseProps {
  value: string;
  onChange: ...;
}

interface UncontrolledInput extends BaseProps {
  defaultValue: string;
  ref: string;
}

export const TextInput:
  React.SFC<ControlledInput | UncontrolledInput> = ({
  type,
  label,
  value,
  ...rest
}) => {

但是,解构 value 会给我一个数组,因为它在 UncontrolledInputProps 上不存在。

我想我需要一个 typeguard,比如:

if (typeof rest.value === 'string') {

我真的无法理解它。任何帮助表示赞赏!

【问题讨论】:

    标签: reactjs typescript interface react-props


    【解决方案1】:

    在官方文档上找到答案: http://www.typescriptlang.org/docs/handbook/advanced-types.html

    所以要编写的 typeguard 如下所示:

    export function isControlled(input: ITextInputControlledProps | 
    ITextInputUncontrolledProps):
      input is ITextInputControlledProps {
        return (input as ITextInputControlledProps).value !== undefined;
    }
    

    然后在我的组件中我可以去:

    if (isControlled(rest)) {
      const { value, onChange } = rest;
      valueProps = { value, onChange };
    } else {
      const { defaultValue, ref } = rest as ITextInputUncontrolledProps;
      valueProps = { defaultValue, ref };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      • 2019-03-07
      相关资源
      最近更新 更多