React.js打字稿接触参数问题

时间:2020-04-14 13:50:32

标签: reactjs typescript react-hooks

const ValidateLogin = (contact) => {
    let errors = {};
    if (!contact.email) {
    } else if (!/\S+@\S+\.\S+/.test(contact.email)) {
        errors.email = "Email address is invalid";
    }
    if (!contact.password) {
        errors.password = "Password is required";
    } else if (contact.password.length < 10) {
        errors.password = "Password needs to be more than 10 characters";
    }
    return errors;
}

export default ValidateLogin

我在(contact)上遇到错误:参数'contact'隐式具有'any'类型。 以及电子邮件和密码:类型“ {}”不存在属性“电子邮件”。

1 个答案:

答案 0 :(得分:0)

您应该使用必需的属性定义联系人的接口或类型别名。这是您可以做到的方式:

interface Contact {
  email: string;
  password: string;
  // include other required properties
}

type Error = Partial<Contact>;

const ValidateLogin = (contact: Contact) => {
  let errors: Error = {};
  // rest of the code
};