In a (React) class I have defined a local identifier to access another type (used by this class):
export class Dropdown extends Component<IDropdownProperties, IDropdownState> {
public static Item = DropdownItem;
}
I can now use that to create a drop down item:
const item = <Dropdown.Item id="id />
Now I want to have an array of items:
const items: Array<Dropdown.Item> = [];
With that Typescript shows the error:
error TS2702: 'Dropdown' only refers to a type, but is being used as a namespace here.
What is the correct syntax to use Dropdown.Item
as an array element type?
Note: I do not explicitly use typeof
here (and when I do, also the single item creation is invalid), but Visual Studio Code shows me:
which is why I'm asking about typeof
. But of course, other solutions are welcome too, if I can keep that Dropdown.Item
syntax. I could just switch to use DropdownItem
instead, but that's not what I'm after.
CodePudding user response:
Probably you need to create an array of created react elements:
const items: Array<React.ReactElement<(typeof Dropdown)['Item']>>
Edit:
If you have access to the type DropdownItem
(e.g. begin exported) where the list items
is defined you can describe it as
const items: React.ReactElement<DropdownItem>[] = []
and here you can check the following approach with functional components
CodePudding user response:
The type Dropdown.Item
refers to the component type, not instance type, which is why simply using typeof
won't work. You need to wrap it in InstanceType
.
Simplified example (using classes instead of React components):
class DropdownItem {
}
class Dropdown {
public static Item = DropdownItem
}
const items: Array<InstanceType<typeof Dropdown.Item>> = [new Dropdown.Item()]