Anthony
Anthony

Reputation: 2418

Typescript filter array of objects

I have an array of objects like so:

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'
}]

How can I filter this array to get the objects where section = 'base'?

If tried

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

And get the error: Property 'section' does not exist on type '{ section: string; key: string; label: string; required: boolean; minLength: number; minLengthErr...'. Property 'section' does not exist on type '{ key: string; label: string; type: string; fieldType: string; required: boolean; minLength: numb...'.

Upvotes: 0

Views: 2211

Answers (3)

Stanislas
Stanislas

Reputation: 2020

@Pradeep Kumar already explained the problem above, but I wanted to add, that you might be interested in reading Type-guards and differentiating types

Upvotes: 1

Jun Kang
Jun Kang

Reputation: 1275

questionConfig: any[] = [{
  section: 'base',
  key: 'firstName',
  label: 'First name',
  type: 'text',
  fieldType: 'input'
  required: true,  
}, { 
  bla: 'bla', 
  ... 
}, { 
  bla: 'bla', 
  test: 'bla', 
  ... 
}];

Since you have an array that seems to be able to have multiple different types of objects pushed to it, you have to cast it as an any[] when it's declared. You're getting that error because when you declare that array in typescript, it implicitly decides that it can only have objects in it of the types it's declared with. If you cast it as an any[], that error Property 'blabla' does not exist on type '{ ... }' should no longer appear because the objects in the array are now of any type.

Upvotes: 1

Pradeep Kumar
Pradeep Kumar

Reputation: 1349

The error message says "'{ section: string; key: string; label: string; required: boolean; minLength: number; minLengthErr...'". That means questionConfig has an object with properties minLength and minLengthErr.

So, it seems like questionConfig has more objects than you have shown in your code snippet and one of the object is missing the property section. Verify where the objects are getting added to questionConfig.

Either, you can fix the object or the better way is to leverage the static type capabilities of TypeScript and define the data types for items in questionConfig.

Upvotes: 3

Related Questions