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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…