56

Confused about the following declaration:

constructor(controls: {[key: string]: AbstractControl}, optionals?: {[key: string]: boolean}, validator?: ValidatorFn, asyncValidator?: AsyncValidatorFn)

What is the type of the controls (first parameter)? Is it an object which is an array of key value pairs where key is string and value is AbstractControl? Thanks!

2 Answers 2

85

Yes, like you guessed, it's a js object with key as string and AbstractControl as values.
For example:

{
    "control1": new Control(),
    "control2": new Control()
}

Edit

You can declare a variable to be of this type in two ways:

let controls: { [key: string]: AbstractControl };

or

interface ControlsMap {
    [key: string]: AbstractControl;
}

let controls: ControlsMap;

or even better:

interface ControlsMap<T extends AbstractControl> {
    [key: string]: T;
}

let controls1: ControlsMap<AbstractControl>;
let controls2: ControlsMap<MyControl>;
2
  • 1
    how would i declare a private variable of this type?
    – mishap
    Commented Apr 19, 2016 at 21:27
  • 1
    @mishap check my revised answer Commented Apr 19, 2016 at 21:32
2

Aside of the above answer, you can also use the Record<Keys,Type> utility type for this situation.

type ControlsMap = Record<string, AbstractControl>;

const mapping: ControlsMap = {
  keyA: new Control(),
  keyB: new Control(),
};

Or with generics:

type ControlsMap<T extends AbstractControl> = Record<string, T>;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.