POV
POV

Reputation: 12025

How to write custom type for array Typescript?

I have interface type:

interface IForm {
   id: number;
   name: string;
} 

I need to write custom type to store this object:

let a = ["one": [IForm, IForm, IForm], "two": [IForm, IForm, IForm]]

How to build this in TypeScript?

In result I need to get all forms by key?

let forms = a["one"]; --> [IForm, IForm, IForm]
forms[0]; --> IForm

Upvotes: 0

Views: 94

Answers (2)

Sefe
Sefe

Reputation: 14017

You can use a mapped type:

type FormList = { [name: string]: IForm[]; };

Or in case "one" and "two" are fixed properties, simply:

interface FormList {
    one: IForm[];
    two: IForm[];
}

This definition implies that properties one and two are always present. If not, you can make them optional:

interface FormList {
    one?: IForm[];
    two?: IForm[];
}

Upvotes: 1

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250216

If the values are arrays of any length and the keys are fixed you can use an interface with those specific fields

 interface FormList [
     one: IForm[];
     two: IForm[];
 }

If the number of items in each array is always 3 you can use a tuple type [IForm, IForm, IForm]

 interface FormList [
     one: [IForm, IForm, IForm];
     two: [IForm, IForm, IForm];
 }

If you want to allow any key to be used you can use an index signature

 interface FormList {
     [key: string] : [IForm, IForm, IForm];
 }

Upvotes: 1

Related Questions