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'.
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.
passwordfrom props and accessing itslengthproperty, but in your props interface you've markedpasswordas optional, i.e. possibly undefined sopassword.lengthcould possibly error if the prop is not passed.InterfaceProps): anyis because I also have several functions passed down too but for the question I removed those as they do not apply. Again my understanding onanycould be misplaced.any(though you really shouldn't be using it as the return type. You can just let TS infer). I'm talking aboutpassword?: string-- you've marked the password prop as optional so there is a possibilitypassword.lengthwill error becausepasswordis undefined which TS is telling you.password: stringover the answer below by R3tep?password. Do whatever suits you, though I'd expect R3tep is more fitting (providing a default value)