我收到以下錯誤:
const validateOptions: ChildFormOptionProps
Argument of type 'number | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.ts(2345)
這是我的 ts 代碼:出現錯誤"parseInt(validateOptions.minlength)"
username: (control: AbstractControl): { [key: string]: ValidatorFn } | null => {
const validateOptions = PatientFormService.controlProps['username'].options;
if (Object.keys(validateOptions).length) {
if (control.value && control.value.length < parseInt(validateOptions.minlength)) {
control.setErrors({ 'incorrect': true });
return control.errors;
}
}
return null;
},
有什么建議可以解決這個問題嗎?
uj5u.com熱心網友回復:
您正在呼叫parseInt,它接受 a string,其值具有型別number | undefined。這是一個型別錯誤,正是 TypeScript 應該幫助您解決的問題。因此,您需要做的是修改代碼,使其不會嘗試使用number | undefinedwith parseInt(這沒有意義)。例如,您可以為undefined案例添加保護,然后按原樣使用數字,或者,如果您有某些理由確保它是整數而不是小數,請在其上酌情使用Math.round/ ceil/ 。floor例如:
username: (control: AbstractControl): { [key: string]: ValidatorFn } | null => {
const validateOptions = PatientFormService.controlProps['username'].options;
if (Object.keys(validateOptions).length) {
if (control.value &&
validateOptions.minLength !== undefined && // ** Guard
control.value.length < validateOptions.minlength) { // ** No parseInt
control.setErrors({ 'incorrect': true });
return control.errors;
}
}
return null;
},
...但是您可能需要對其進行調整,我必須在其中做出一些小假設。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/454267.html
