Paul W Paul W - 29 days ago 398
TypeScript Question

NavItem return type in react, reactstrap

I've created a function that takes props and makes an array of . I want to know the return type I can use for this function so that it is type safe. I tried typeof and it returns object. I want the function to look like this:

createNavItems(names: Array<string>):***Not sure what to put here*** {
linkItems = names.map(name => {
<NavItem key={name}>name</NavItem>
}
return linkItems;
}


Thanks for the help or suggestions.

Answer Source

The array returned from the function createNavItems has the following return type: Array<React.ReactElement<{}>>

Here is a complete example, which also fixes several small errors in the TypeScript code of the question:

import * as React from "react";

function createNavItems(names: Array<string>): Array<React.ReactElement<{}>> {
   return names.map(name => (
       <NavItem key={name}>{name}</NavItem>
   ));
}

class NavItem extends React.Component {
    render() {
        return (
            <div className="nav-item">{this.props.children}</div>
        );
    }
}