Typescript array of key value pairs declaration

萝らか妹 提交于 2019-11-29 04:57:55

问题


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!


回答1:


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>;


来源:https://stackoverflow.com/questions/36729643/typescript-array-of-key-value-pairs-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!