我是 Typescript 的新手,目前正在将我们的应用程序从 React JSX 转换为 TS,所以如果我误解了错误,请告诉我。我得到Object is possibly 'undefined'一个prop string是从父母传下来的component。所述string被内限定INITIAL_STATE在`作为父private static INITIAL_STATE = { password: ''};这意味着子组件中的propforpassword永远不应该是undefined. 子组件是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;OnpwLength我看到了Object is possibly 'undefined'on 的错误password prop。对{ pwUpCase, pwLwCase, pwChar, pwDigit }在password prop我收到的错误Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.在这种情况下,我的想法是props password永远不会undefined因为它在父组件中具有初始state值''。我是否仍然需要检查password未定义?或者也许正确的方法应该是移动isInvalid到父组件?我宁愿我不需要,所以任何建议都会非常有帮助。
1 回答
犯罪嫌疑人X
TA贡献2080条经验 获得超4个赞
password
在您的界面上是可选的。
因此,您需要将默认值传递给password
.
喜欢:
const ChildComponent = ({ password = '' }: InterfaceProps): any => { -----------------------------------^^^^
添加回答
举报
0/150
提交
取消