Soy nuevo en TypeScript. Tengo un problema al mostrar this.state.something dentro del método render o asignarlo a una variable dentro de una función.
Eche un vistazo a la pieza de código más importante:
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> ); } }El error dice: "[ts] La propiedad 'playOrPause' no existe en el tipo 'ReadOnly<{}>'.
Intenté declarar la propiedad playOrPause como un tipo de cadena y no funcionó. ¿Qué me estoy perdiendo aquí para que funcione?
Debe declarar que su componente está utilizando la interfaz State, utilizada por 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> ); } }En caso de que alguien se pregunte cómo implementarlo en componentes funcionales con ganchos (no en una clase) :
const [value, setValue] = useState<number>(0);useState es una función genérica, eso significa que puede aceptar un parámetro de tipo. Este parámetro de tipo le dirá a TypeScript qué tipos son aceptables para este estado.
En mi caso (trabajando con TypeScript, y el valor del estado era en realidad un booleano) tuve el mismo problema, lo arreglé pasando el valor del estado que quería marcar como salida a String():
import React, { Component } from 'react'; interface ITestProps { name: string; } interface ITestState { toggle: boolean; } class Test extends Component<ITestProps, ITestState> { constructor(props: ITestProps) { super(props); this.state = { toggle: false, }; this.onClick = this.onClick.bind(this); } onClick() { this.setState((previousState, props) => ({ toggle: !previousState.toggle, })); } render() { return ( <div> Hello, {this.props.name}! <br /> Toggle state is: {String(this.state.toggle)} </div> ) } }