Sunday, September 10, 2017

Typescript Array.Map


TypeScript made me go back to web development again, bringing in the compile time type checks really makes it easier to write correct code faster.
But sometimes it is a little tricky to figure out the syntax. For example last night when I tried to store the result from an array.map call in a variable. Most of the examples I found used the var keyword and pretty much ignoring the type check making me wonder why even bother with TypeScript if you don't use the types?

So, I wanted to try the array.map in the render method of a React JSX file to render a list of items. The end result was something like this:
public render() {
 const itemNames: string[] = ["Item One", "Item Two"];
 let itemNamesRender: JSX.Element[] = equipmentNames.map((name: string) => <li>{name}</li>);
 return <div>
  <h1>My Items</h1>

  <ul>{equipmentNamesRender}</ul>
 </div>;
}

Where the
let result: JSX.Element[] = array.map()
is the key. So pretty much just like all other variable declarations. The issue I had turned out to be that I didn't know that the type was JSX.Element, instead I was trying to force it to a string type.

Hope this helps someone out there. : )

No comments:

Post a Comment