我是 Typescript 的新手,目前正在將我們的應(yīng)用程序從 React JSX 轉(zhuǎn)換為 TS,所以如果我誤解了錯(cuò)誤,請(qǐng)告訴我。我得到Object is possibly 'undefined'一個(gè)prop string是從父母?jìng)飨聛?lái)的component。所述string被內(nèi)限定INITIAL_STATE在`作為父private static INITIAL_STATE = { password: ''};這意味著子組件中的propforpassword永遠(yuǎn)不應(yīng)該是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 的錯(cuò)誤password prop。對(duì){ pwUpCase, pwLwCase, pwChar, pwDigit }在password prop我收到的錯(cuò)誤Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.在這種情況下,我的想法是props password永遠(yuǎn)不會(huì)undefined因?yàn)樗诟附M件中具有初始state值''。我是否仍然需要檢查password未定義?或者也許正確的方法應(yīng)該是移動(dòng)isInvalid到父組件?我寧愿我不需要,所以任何建議都會(huì)非常有幫助。
對(duì)象可能在 Typescript 中的字符串值“未定義”
尚方寶劍之說(shuō)
2021-07-09 14:01:55