I have the error: Type (string | undefined)[] is not assignable to type string | string[] | undefined, because my function this.errors get the type string | string[] | undefined. But before to return the array I filtered it with undefined. It means there is no undefined. And the value can be string or undefined. The definition of setErrors return array of errors.
This is my error:
This is my function:
this.setErrors(() => {
const errors = validators.map(val => val(this.inputValue));
const filteredErrors = errors.filter(el => el);
return filteredErrors && filteredErrors.length !== 0 ? filteredErrors : undefined;
});
Validators:
const REGEXP_UPPERCASE = /[A-Z]/;
const REGEXP_LOWERCASE = /[a-z]/;
const REGEXP_ONE_DIGIT = /.*[0-9].*/;
export const newPasswordValidators = (args: { min: number; max: number }) => {
const { min, max } = args;
return {
minMaxLength: (value?: string) => value && value.length < min || value.length > max ? 'Not valid length' : undefined,
requiredToFill: (value?: string) => !value ? 'Required to fill.' : undefined,
uppercaseLetter: (value?: string) => value && !REGEXP_UPPERCASE.test(value) ? 'Use at least one uppercase letter.' : undefined,
lowercaseLetter: (value?: string) => value && !REGEXP_LOWERCASE.test(value) ? 'Use at least one lowercase letter.' : undefined,
atLeastOneDigit: (value?: string) => value && !REGEXP_ONE_DIGIT.test(value) ? 'Use at least one digit.' : undefined,
};
};
Super class method:
public setErrors(errors: string | string[] | undefined | (() => (string | string[] | undefined))) {
this._errors = errors;
}
Can you tell me please how can I get rid from this error?
validators? What isthis.inputValue? What is the definition ofthis.setErrors?this.setErrorsandvalidatorsmap(). Your validators can returnundefinedor string with error. It looks like TS filter typing is not smart enough, so you still have (string | undefined)[] after its run. So the best option is typecasting until it's fixed.