O
O
oddwang2022-02-19 19:49:03
typescript
oddwang, 2022-02-19 19:49:03

How to indicate in the TypeScript interface that an array can contain many objects of the same type?

Perhaps I don’t understand something, but I want to indicate that the array will contain many objects of the same type, how can I indicate this? Specified interface:

const state: StateType = {
    user: 'User',
    columns: [
        {title: 'ToDo', cardList: []},
        {title: 'In progress', cardList: []},
        {title: 'Testing', cardList: []},
        {title: 'Done', cardList: []},
    ],
    cards: [],
}

interface StateType {
    user: string,
    columns: [
        {title: string, cardList: []}
    ]
}


In this case, it gives the following error:
Тип "[{ title: string; cardList: []; }, { title: string; cardList: []; }, { title: string; cardList: []; }, { title: string; cardList: []; }]" не может быть назначен для типа "[{ title: string; cardList: []; }]".
  Число элементов в источнике — 4, но целевой объект разрешает только 1.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Aetae, 2022-02-19
@oddwang

[ {title: string, cardList: []} ]is not an array filled with values ​​of type , it is a tuple of one value of this type. An array is denoted like this or like this . A tuple is used when a specific number of values ​​of a specific type is needed at specific positions. {title: string, cardList: []}

A
Alex, 2022-02-19
@Kozack

More or less like this

type ToDo = {title: 'ToDo', cardList: []}
type Testing = {title: 'Testing', cardList: []}

interface StateType {
    user: string,
    columns: (ToDo | Testing)[]
}

const state: StateType = {
    user: 'User',
    columns: [
        {title: 'ToDo', cardList: []},
        {title: 'Testing', cardList: []},
    ],
}

https://www.typescriptlang.org/play?#code/C4TwDgpg...
Or even like this:
enum kinds  {
    ToDo = 'ToDo',
    Testing = 'Testing',
}

type Column = {title: kinds, cardList: []}

interface StateType {
    user: string,
    columns: Column[]
}

const state: StateType = {
    user: 'User',
    columns: [
        {title: kinds.ToDo, cardList: []},
        {title: kinds.Testing, cardList: []},
    ],
}

https://www.typescriptlang.org/play?ssl=19&ssc=2&p...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question