14

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 :)

2 Answers 2

35
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 }[];
}
Sign up to request clarification or add additional context in comments.

5 Comments

isn't there some way to add he first two together? something like : export interface TrueFalseItem: [ ] { }
Not quite, but see the second example for a single definition version. You may have unnecessary nesting in your data structures if you need an interface like this to describe it.
I think what I don't understand is Array<{'text'; 'value'}> where there is a semicolon inside (the why there isn't it a comma part)
That is called an object literal type. You can use either a semi-colon or a comma in an object literal type. Any type declaration, such as an interface, is comprised of name: type elements. When you omit the type of an element, it defaults to any. That means that { text; value } is the same type as { text: any; value: any }. The quotes are optional.
7

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() ...)

1 Comment

Defining an empty interface is misleading and considered a bad practice given the structurally typed nature of TypeScript. Use export type ItemList = Array<ItemListValue>; which makes the intent clear and the code clean

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.