Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

reactjs - Converting JavaScript React Component into TypeScript

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?

question from:https://stackoverflow.com/questions/65850860/converting-javascript-react-component-into-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...