Converting JavaScript React Component into TypeScript

Viewed 100

I am going to convert one JavaScript component I have, into TypeScript but I am new to TypeScript and I do not know where I have to start for converting my JavaScript component to TypeScript.
I put just the main parts of component into my question but briefly my component includes:

Mycomponent:

class App extends React.Component {

 state = { sections: [
  {
  "title": "Popular",
  "items": [
    {
      "name": "Lorem",
      "online": true,
     } ]
    } 
    ] 
    }

render() {
   var sections = this.state.sections.map(function(section, index) {

  return (
    <div className="container-fluid">
      <Section section={section} key={index}/>
    </div>
  )
});

return( 
 <div> {sections} </div>
)
}
}
export default App;

How can I have this JavaScript Component in TypeScript?

1 Answers
class App extends React.Component {

 state: ComponentState = { 
   sections: [
     {
       "title": "Popular",
       "items": [
         {
           "name": "Lorem",
           "online": true,
         }
       ]
      } 
    ]}

  render() {
     var sections = this.state.sections.map(function(section, index) {

     return (
         <div className="container-fluid">
           <Section section={section} key={index}/>
          </div>
       )
    });

    return( 
      <div> {sections} </div>
    )
  }
}

interface ComponetState {
  sections?: {
    title: string
    online: boolean
  }[]
}

}

export default App;

The primary benefit of using typescript is that it makes javascript strictly typed. As you can see I have the interface ComponentState. This interface is a type that can be assigned to a variable. This is what I did to your state variable. As you can see, the shape of the interface describes the data that can be in your state. All optional data is denoted with the ? character next to its name in the interface.

Typescript also has enums and generic types.

Related