typescript 键值对声明的打字稿数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36729643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:04:41  来源:igfitidea点击:

Typescript array of key value pairs declaration

arraystypescriptkey-value

提问by mishap

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!

控件的类型是什么(第一个参数)?它是一个键值对数组的对象,其中键是字符串,值是 AbstractControl?谢谢!

回答by Nitzan Tomer

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

是的,就像你猜的那样,它是一个 js 对象,键作为字符串和AbstractControl值。
例如:

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