微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

拒绝在 prop 中具有特定类型的函数中的参数

如何解决拒绝在 prop 中具有特定类型的函数中的参数

我有一个组件,它准备好接收一个名为 type 的参数,它可以是电子邮件、手机号码、cep、密码四个选项之一。如果属性类型值密码,则不应解析属性图标和 onPressIcon。我已经输入了这个道具如下:

type TextInputT = {
  type: 'email' | 'mobileNumber' | 'cep' | 'password';
  name: string;
  label: string;
  onPressIcon: () => void;
  icon: string;
};

如果 textinput 的类型是密码,如何使 icononPressIcon 道具无效?

我已经试过了

type TextInput = {
  type: 'password';
  name: string;
  label: string;
};

type CustomTextInput = {
  type: 'email' | 'mobileNumber' | 'cep';
  name: string;
  label: string;
  onPressIcon: () => void;
  icon: string;
};

export type TextInputT = TextInput | CustomTextInput;

但是在组件道具类型分配中抛出错误如下

enter image description here

EDIT1:我的 TextInput.tsx

const TextInput: React.FC<TextInputT> = ({
  type,name,label,onPressIcon,icon,}) => {
  const inputValueRef = React.useRef(null);

  const [isFocused,setIsFocused] = React.useState<boolean>(false);
  const [valueShown,setValueShown] = React.useState<boolean>(false);

  const [field,Meta,helpers] = useField(name);

  const hasError: boolean = Meta.touched && typeof Meta.error !== 'undefined';
  const error: string = Meta.touched && Meta.error;

  return (
    <Container>
      <Content
        active={isFocused}
        error={hasError}
        disabled={false}
        onPress={() => inputValueRef?.current?.focus()}
        activeOpacity={1}>
        {(isFocused || Meta.touched) && (
          <Label active={isFocused} error={hasError} disabled={false}>
            {label}
          </Label>
        )}
        <InputBox>
          <InputValue
            ref={inputValueRef}
            secureTextEntry={type === 'password' && !valueShown}
            onFocus={() => setIsFocused(true)}
            placeholder={!isFocused ? label : ''}
            value={getFormattedValue({
              value: field.value,mask: type,})}
            onChangeText={field.onChange(name)}
            onBlur={() => [setIsFocused(false),helpers.setTouched(true)]}
          />
          {type === 'password' && (
            <IconBox onPress={() => setValueShown(!valueShown)}>
              <IconDynamic
                name={`${valueShown ? 'EyeClosed' : 'Eye'}`}
                width={24}
                height={24}
                fill={colors.C.default}
              />
            </IconBox>
          )}
          {icon && onPressIcon && (
            <IconBox onPress={onPressIcon}>
              <IconDynamic
                name={icon}
                width={24}
                height={24}
                fill={colors.C.default}
              />
            </IconBox>
          )}
        </InputBox>
      </Content>
      {hasError && (
        <ErrorBox>
          <TextError>{error}</TextError>
        </ErrorBox>
      )}
    </Container>
  );
};

export default TextInput;

解决方法

TS 更安全的选择是在检查 onPressIcon 属性之前禁止使用 type

type TextInput = {
  type: 'password';
  name: string;
  label: string;
};

type CustomTextInput = {
  type: 'email' | 'mobileNumber' | 'cep';
  name: string;
  label: string;
  onPressIcon: () => void;
  icon: string;
};

export type Union = TextInput | CustomTextInput;

const comp=(prop:Union)=>{
    if(prop.type==='password'){
        const x = prop.onPressIcon // error
    }
    if(prop.type==='email'){
        const x = prop.onPressIcon // ok
    }
}

为了更好地理解它,请看下一个例子:

type TextInput = {
  type: 'password';
  name: string;
  label: string;
};

type CustomTextInput = {
  type: 'email' | 'mobileNumber' | 'cep';
  name: string;
  label: string;
  onPressIcon: () => void;
  icon: string;
};

export type Union = TextInput | CustomTextInput;

type Keys = keyof Union // "type" | "name" | "label" < ------ only properties which are common for both type

想象一下,TS 允许您在不检查 onPressIcon 属性的情况下获取 type 属性。

这将打破工会的整个想法。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?