0

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
2
  • you could check the type autogenerated by typescript for a suggestion. Commented Jun 27, 2018 at 11:00
  • What's with the squery braces in let a = [ ... ]. Do you mean curly braces let a = { ... }? Commented Jun 27, 2018 at 11:06

2 Answers 2

1

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

6 Comments

What is difference between these type? What is more priority?
I tried fill object based this type: let a: FileList; a = { "profile": [{ id: 1, name: "ss" }}
I don't understand the meaning of "priority" here. The difference is that with a mapped type you are free to use any key, not just "one" and "two". With an interface you specify that only "one" and "two" are allowed.
You are missing a bracket: let a: FileList; a = { "profile": [{ id: 1, name: "ss" }]}
It is still incorrect: type FormList = { [name: string]: IForm[]; }; let a: FileList; a = { "profile": [{ id: 1, name: "ss" }]}
|
1

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

3 Comments

What is difference between type and interface definition? Is is possible to write using type?
In this case there is not much difference, you can write using type as well type FormList = { [key: string] : [IForm, IForm, IForm]; }
Mustumesc mult! :)

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.