A
A
Alex Mirgorodskiy2021-04-01 14:02:10
typescript
Alex Mirgorodskiy, 2021-04-01 14:02:10

How to correctly describe a prop, which can be both an object and an array with objects of the same type?

Good day to all, I ran into an uncomfortable situation in ts.
My props can be both an object there and an array of objects

export interface ControlProps {
    value?: string | number
}

export interface ControlsProps {
    [propName: string]: ControlProps | ControlProps[]
}

export interface FormProps {
    controls: ControlsProps | ControlsProps[]
}


Partially, this option works, but in many places it starts to swear, for example, that ControlsProps does not have a foreach method (when I work with the controls object), and so on.

Do not tell me how to handle the correct situations in general, maybe the approach with ControlsProps | ControlsProps[] is fundamentally wrong, if so point in the right direction. Thanks in advance

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Yarkov, 2021-04-01
@AlexWeb6667

for example that ControlsProps does not have a foreach method (when I work with the controls object)

Well, checks are needed, like
if (Array.isArray(prop)) {
  // тут метод forEach вызывать можно, ибо массив
}

can approach with ControlsProps | ControlsProps[] is fundamentally wrong

Well, in the root or not - it's up to you, but I would prefer to always pass an array, albeit from one element.

D
Dmitry Belyaev, 2021-04-01
@bingo347

in many places it starts to swear, for example, that ControlsProps does not have a foreach method
everything swears correctly, according to your types, ControlsProps is a plain object, where the key can be any string, and all values ​​​​are ControlProps or an array of ControlProps. An arbitrary object does not have a forEach method.
Do not tell me how to handle the correct situations in general, maybe the approach with ControlsProps | ControlsProps[] is fundamentally wrong
https://www.typescriptlang.org/docs/handbook/2/nar...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question