I am getting following errors:
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)
Here is my ts code : getting error at "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;
},
any suggestion to fix this issue?
CodePudding user response:
You're calling parseInt
, which accepts a string
, with a value that has the type number | undefined
. That's a type error, exactly what TypeScript is supposed to help you with. So what you need to do is modify the code so it doesn't try to use a number | undefined
with parseInt
(which makes no sense). For instance, you might add a guard for the undefined
case, then either use the number as-is or, if you have some reason for ensuring it's an integer rather than fractional, use Math.round
/ceil
/floor
as appropriate on it. For instance:
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;
},
...but you may have to tweak that, I had to make a couple of minor assumptions in there.