简体   繁体   English

将字符串数组的动态值分配给 typescript 中 object 的属性

[英]Assigning dynamically values of string array to properties of an object in typescript

suppose a component named searchBox receives tow inputs: @Input() titles: string[] and @Input() model: Object , that the number of titles values is equal to number of model properties.假设名为searchBox的组件接收两个输入: @Input() titles: string[]@Input() model: Object标题值的数量等于Z20F35E630DAF44DBFA4C3FZD58F的数量。 searchBox generates input box to number of titles length, and gets searching subjects from user and push them into a string array named titlesValues . searchBox生成标题长度的输入框,并从用户那里获取搜索主题并将它们推送到名为titlesValues的字符串数组中。 so, searchBox should assigns the values of titlesValues to model properties peer to peer and outputs the model via @Output resultModel: Object .因此, searchBox应该将titlesValues 的值分配给model点对点属性,并通过@Output resultModel: Object I tried to access each model property dynamically for assigning to, therefore I encoded this scenario in the following:我尝试动态访问每个model属性以进行分配,因此我在下面对这个场景进行了编码:

let i =0;
  Object.keys(this.model).forEach((key) => {
     this.model[key] = this.titlesValues[i];
   });

although I tested much statements and alternative codes to get desire result, but it gets bellow error:虽然我测试了很多语句和替代代码以获得期望的结果,但它得到以下错误:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Object' .元素隐式具有 'any' 类型,因为 'string' 类型的表达式不能用于索引类型 'Object'

how can I implement this scenario?我该如何实现这个场景? Best regards.此致。

try to change this:尝试改变这一点:

@Input() titles: any[]

To overcome the error, you can either explicitly define model to be of type any :要克服该错误,您可以将model显式定义为any类型:

@Input() model: any;

or或者

define a new interface for the model and use it as:model定义一个新接口并将其用作:

interface Model {
    [index: string]: string;
}

@Input() model: Model;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM