Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using state in react with TypeScript

I am new to TypeScript. I've got a problem with displaying this.state.something inside the render method or assigning it to a variable inside a function.

Have a look at the most important piece of code:

interface State {     playOrPause?: string; }  class Player extends React.Component {     constructor() {         super();          this.state = {             playOrPause: 'Play'         };     }      render() {         return(             <div>                 <button                     ref={playPause => this.playPause = playPause}                     title={this.state.playOrPause} // in this line I get an error                     >                     Play                 </button>            </div>         );     } } 

The errors says: "[ts] Property 'playOrPause' does not exist on type 'ReadOnly<{}>'.

I tried to declare the playOrPause property to be a type of string and it didn't work. What am I missing here to make it work?

like image 654
Maciej S. Avatar asked Oct 28 '17 08:10

Maciej S.


People also ask

Can we use Redux with TypeScript?

As of React-Redux v8, React-Redux is fully written in TypeScript, and the types are included in the published package. The types also export some helpers to make it easier to write typesafe interfaces between your Redux store and your React components.


2 Answers

You need to declare that your component is using the State interface, it used by Typescript's Generics.

interface IProps { }  interface IState {   playOrPause?: string; }  class Player extends React.Component<IProps, IState> {   // ------------------------------------------^   constructor(props: IProps) {     super(props);      this.state = {       playOrPause: 'Play'     };   }    render() {     return(       <div>         <button           ref={playPause => this.playPause = playPause}           title={this.state.playOrPause} // in this line I get an error         >           Play         </button>       </div>     );   } } 
like image 95
felixmosh Avatar answered Oct 06 '22 15:10

felixmosh


In case anyone is wondering how to implement it in functional components with hooks ( not in a class):

const [value, setValue] = useState<number>(0); 

useState is a generic function, that means that it can accept a type parameter. This type-parameter will tell TypeScript which types are acceptable for this state.

like image 35
PedroMiotti Avatar answered Oct 06 '22 15:10

PedroMiotti