【问题标题】:Typescript filter array of objectsTypescript过滤器对象数组
【发布时间】:2018-02-10 05:29:03
【问题描述】:

我有一个这样的对象数组:

questionConfig = [{
  section: 'base',
  key: 'firstName',
  label: 'First name',
  type: 'text',
  fieldType: 'input'
  required: true,  
 },
 {
  section: 'dynamic'
  key: 'emailAddress',
  label: 'Email',
  type: 'email',    
  fieldType: 'input',
  required: true,     
},
{     
  key: 'primaryPhone',
  label: ' primary phone',
  type: 'phone',     
  fieldType: 'input'
},
{    
key: 'something',
label: 'dgfdsfgds',
options: [
  {key: 1, value: 'dsfgdsg'},
  {key: 2, value: 'dfgdsfg'},
  {key: 3, value: 'dsfgdsgds'},
  {key: 4, value: 'dsfgdgsf'}
],    
fieldType: 'dropdown'
}]

如何过滤此数组以获取 section = 'base' 的对象?

如果尝试过

let questionBaseSection = this.questionConfig.filter(question => question.section === 'base' )

并得到错误: 类型 '{ section: string; 上不存在属性 'section'键:字符串;标签:字符串;必需:布尔值; minLength:数字; minLengthErr...'。 类型 '{ key: string; 上不存在属性 'section'标签:字符串;类型:字符串;字段类型:字符串;必需:布尔值; minLength: 麻木...'。

【问题讨论】:

  • questionConfig 是如何声明的?
  • 您的数组中似乎有一个项目没有section 属性。第二个错误说明了这一点。检查这个。
  • 只有你在上面看到的。这不正确吗?
  • TypeScript 的重点是使用类型。如果你不定义类型,我建议你使用普通的 ECMAScript。
  • 正如所写,这应该没有什么问题。错误说 Property 在类型上不存在,所以您是否随时将任何其他对象添加到数组中?

标签: typescript ecmascript-6 angular-cli


【解决方案1】:

错误消息显示“'{ 部分:字符串;键:字符串;标签:字符串;必需:布尔值;minLength: number; minLengthErr...'”。这意味着 questionConfig 有一个具有属性 minLengthminLengthErr 的对象。

因此,questionConfig 的对象似乎比您在代码 sn-p 中显示的要多,并且其中一个对象缺少属性 section。 验证对象被添加到questionConfig 的位置。

您可以修复对象,或者更好的方法是利用 TypeScript 的静态类型功能并为 questionConfig 中的项目定义数据类型。

【讨论】:

  • 很好的解释。我在真实代码中的数组还有 2 个对象。这些对象缺少“部分”属性,我错误地认为过滤器可以处理这种情况。我如何使用过滤器但处理对象中是否存在属性?
【解决方案2】:
questionConfig: any[] = [{
  section: 'base',
  key: 'firstName',
  label: 'First name',
  type: 'text',
  fieldType: 'input'
  required: true,  
}, { 
  bla: 'bla', 
  ... 
}, { 
  bla: 'bla', 
  test: 'bla', 
  ... 
}];

由于您的数组似乎能够向其推送多种不同类型的对象,因此您必须在声明时将其转换为any[]。您收到该错误是因为当您在 typescript 中声明该数组时,它隐含地决定它只能在其中包含声明它的类型的对象。如果将其转换为 any[],则该错误 Property 'blabla' does not exist on type '{ ... }' 将不再出现,因为数组中的对象现在属于 any 类型。

【讨论】:

    【解决方案3】:

    @Pradeep Kumar 已经解释了上面的问题,但我想补充一下,你可能有兴趣阅读 Type-guards and differentiating types

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-12
      • 2020-06-24
      • 2017-09-06
      • 1970-01-01
      • 2020-02-04
      • 1970-01-01
      • 2019-10-03
      • 2018-01-27
      相关资源
      最近更新 更多