Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define Interface containing array of objects

I have an object that is used in many parts of my code so I want to export it as an interface. My object is like this :

 trueFalse: {'itemList' : Array<{'text'; 'value'}>} = {
    itemList: [
      {text: 'foundItem', value: true},
      {text: 'foundItem', value: false}
    ]
  };

I tried to import it this way but it doesn't work :

export interface ITrueFalse {
  text: string = 'foundItem',
  value: boolean
  itemList: Array<{'text';'value'}>
}

I want to implement the above interface in some way like this:

trueFalse: {'itemList' : ITrueFalse} = {
    itemList : [{},{}]
;

As you can see I don't have much idea of typescript interfaces. I've only done basic type definition. So I don't know what I'm doing wrong. Thank you for any suggestions :)

like image 252
Bijay Timilsina Avatar asked Apr 28 '17 10:04

Bijay Timilsina


2 Answers

export interface TrueFalseItem {
  text: string;
  value: boolean;
}


export interface TrueFalseListWrapper { // renamed from ITrueFalse
  itemList: TrueFalseItem[];
}

You can also write the item type itself inline which is convenient if you only need to refer to it as part of the structure of TrueFalseListWrapper

export interface TrueFalseListWrapper {
  itemList: { text: string, value: boolean }[];
}
like image 107
Aluan Haddad Avatar answered Oct 15 '22 08:10

Aluan Haddad


Here is another solution that I prefer:

interface ItemListValue {
  text: string,
  value: boolean,
}

export interface ItemList extends Array<ItemListValue > {

}
let result: ItemList;

With this solution you can use all properties and methods of the Array (like: length, push(), pop(), splice() ...)

like image 36
Amel Avatar answered Oct 15 '22 08:10

Amel