Answer the question
In order to leave comments, you need to log in
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[]
}
Answer the question
In order to leave comments, you need to log in
for example that ControlsProps does not have a foreach method (when I work with the controls object)
if (Array.isArray(prop)) {
// тут метод forEach вызывать можно, ибо массив
}
can approach with ControlsProps | ControlsProps[] is fundamentally wrong
in many places it starts to swear, for example, that ControlsProps does not have a foreach methodeverything 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 wronghttps://www.typescriptlang.org/docs/handbook/2/nar...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question