简体   繁体   中英

Object is possibly 'undefined' in Typescript on string value ''

I am new to Typescript and currently converting our application from React JSX to TS so please let me know if I am misunderstanding the error.

I am getting Object is possibly 'undefined' on a prop string that is passed down from a parent component . The string is defined within INITIAL_STATE in the `parent as

private static INITIAL_STATE = {
  password: ''
};

Meaning that the prop for password in the child component should never be undefined . The child component is

interface InterfaceProps {
  onlyOneLeft?: boolean;
  isEnabled?: boolean;
  signInMethod?: any;
  onUnlink?: any;
  password?: string;
  passwordTwo?: string;
  handleFormSubmit?: any;
  handleInputChange?: any;
}

const ChildComponent = ({ password }: InterfaceProps): any => {
  const regUpCase = new RegExp('^(?=.*[A-Z])');
  const regLwCase = new RegExp('^(?=.*[a-z])');
  const regDigit = new RegExp('^(?=.*[0-9])');
  const regChar = new RegExp('^(?=.*[*@!#%&()^~{}_-])');

  const pwLength = password.length >= 8;
  const pwUpCase = regUpCase.test(password);
  const pwLwCase = regLwCase.test(password);
  const pwChar = regChar.test(password);
  const pwDigit = regDigit.test(password);
  const pwSpecial = pwChar || pwDigit;

  const isInvalid =
    !pwLength || !pwUpCase || !pwLwCase || !pwSpecial || password === '';

  return isInvalid ? (
    ... // return when password isInvalid
  ) : (
    ... // return when password !isInvalid
  );
};

ChildComponent.propTypes = {
  password: PropTypes.string
};

export default ChildComponent;

On pwLength I am seeing the error of Object is possibly 'undefined' on the password prop .

On { pwUpCase, pwLwCase, pwChar, pwDigit } on the password prop I am getting an error of Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'. Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.

My thought in this scenario is that the props password will never be undefined as it has an initial state of '' in the parent component.

Am I required to still check for password to undefined? Or perhaps should the correct method be to move isInvalid to the parent component? I would prefer I didn't need to, so any suggestions would be very helpful.

password is optional on your interface.

So you need to pass a default value to password .

Like:

const ChildComponent = ({ password = '' }: InterfaceProps): any => {
-----------------------------------^^^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM