0

For example I have this class property:

public messages : Array<{session: string, messages: [{profile_picture ? : string, type: string, text: string}]}> = []

I want to make something like this public messages : MessagesInterface in order to be able to use that interface in different places.

I know that is should like something like this:

export interface MessagesInterface {
    session: string, 
    messages: [{profile_picture ? : string, type: string, text: string}]
}

But how to specify that it is array of messages?

Kin
  • 4,466
  • 13
  • 54
  • 106

1 Answers1

0

You have a couple of options. You can specify an indexable interface as:

export interface MessagesInterface {
    [key:number]: {
        session: string, 
        messages: [{profile_picture ? : string, type: string, text: string}]
    }
}

Or instead export a type

export type MessagesInterface = {
    session: string, 
    messages: [{profile_picture ? : string, type: string, text: string}]
}[]

I'd still encourage breaking it into multiple interfaces to help readability whichever path you choose.

Paarth
  • 9,687
  • 4
  • 27
  • 36
  • No. The whole `MessagesInterface` is array which consists of objects which includes `session` and `messages` – Kin Jul 04 '17 at 07:09
  • What difference is between type and interface? – Kin Jul 04 '17 at 07:16
  • https://stackoverflow.com/questions/37233735/typescript-interfaces-vs-types – Paarth Jul 04 '17 at 07:24
  • In this specific case, the type will carry the other array functions (.length and such) while the interface will not. The interface is purely indexable, the type is an actual array. You could make the interface extend Array if you wanted to achieve both. – Paarth Jul 04 '17 at 07:27