Currently my component contains an interface that has value: ReactSelectOptions | ReactSelectOptions[];
and it's defined as
export interface ReactSelectOptions {
value: string | number;
label: string;
}
but if I try to access value.label
or value[0].label
I get an error saying
Element implicitly has an 'any' type because expression of type '"label"' can't be used to index type 'ReactSelectOptions | ReactSelectOptions[]'.
and
Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'ReactSelectOptions | ReactSelectOptions[]'.
What's the issue here and how can I approach this?
Btw, I also have another property isMulti: boolean
that's why I sometimes need my value to be array of objects if that helps.
CodePudding user response:
The problem stems from the fact that value
could be ReactSelectOptions
or an array ReactSelectOptions[]
. TS doesn't know what the type is gonna be as this is gonna be decided at runtime, so it forces you to make compile time checks.
For your case checking if the var is an array should suffice. Something similar to this should get you going:
interface ReactSelectOptions {
value: string | number;
label: string;
}
function someF(maybeArr:ReactSelectOptions | ReactSelectOptions[]) {
if (Array.isArray(maybeArr)) {
maybeArr[0].label
} else {
maybeArr.label
}
}