keldar keldar - 2 months ago 31
TypeScript Question

Angular 2 - Custom Validator Syntax

Please can somebody explain the following TypeScript syntax to me:

{[s: string]: boolean}


This is the return type for a
ValidatorFn
within Angular 2. Particularly, what does the array:
[s: string]
denote?

While writing my own custom
ValidatorFn
function, what is the purpose of the boolean field? There seems to be no difference in the following:

startsWithZero(control: FormControl): {[s: string]: boolean} {
if (control.value.indexOf('0') !== 0) {
return {'does not start with zero': true};
}

return null;
}


vs.

startsWithZero(control: FormControl): {[s: string]: boolean} {
if (control.value.indexOf('0') !== 0) {
return {'does not start with zero': false};
}

return null;
}


The Angular documentation is a little abstract in this regard and cannot find much on Google. Thanks!

Answer

In this example, the type annotation {[s: string]: boolean} means a dictionary where the key is a string and the value is a boolean.

Such types are referred to as Indexable Types. This a typical way of describing dictionaries (a.k.a. hash maps).

In Angular 2, the ValidatorFn is typed as:

export interface ValidatorFn {
    (c: AbstractControl): {
        [key: string]: any;
    };
}

...a function that takes an AbstractControl and returns a dictionary - the key identifies the validation rule, e.g. maxLength, and the value can be anything that explains why the rule failed, e.g. {'requiredLength': maxLength, 'actualLength': v.length}. It doesn't have to be a boolean.

Examples from Angular 2 source are here.

Comments