Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'string' is not assignable to type 'Position'

I'm modifying React js to ts now. It is Class Componenet.

I want to get css settings by props and apply it to Element.

How should I fix this?

render(){return(
<span style={{
          position: this.props.position ,
          left: this.props.left,
          top: this.props.top,
          height: this.props.height,
          width: this.props.width
     }} /> </span>)}
like image 289
Yongjun Park Avatar asked Jun 06 '26 06:06

Yongjun Park


2 Answers

Typescript expects the string to be literally one of the options of the position property - absolute, relative etc One way to solve it is to tell it that you know the type will be ok, like so :

<span style={{
          position: this.props.position,
          left: this.props.left,
          top: this.props.top,
          height: this.props.height,
          width: this.props.width
     }:  as React.CSSProperties} /> </span>)}

Another option is to go where the position property is originally defined (parent element) and let Typescript enforce type, for example:

const styles: ('absolute' | 'relative' | 'fixed') = 'absolute';
like image 92
Skarlinski Avatar answered Jun 07 '26 19:06

Skarlinski


There is no need to cast the object but declare the type React.CSSProperties when initializing.

  function MyComponent(props) {
    const styles: React.CSSProperties = {
      position: this.props.position,
      left: this.props.left,
      top: this.props.top,
      height: this.props.height,
      width: this.props.width
    };


    return (
      <span style={styles}></span>
    );
  }
like image 44
Kevin Farrugia Avatar answered Jun 07 '26 18:06

Kevin Farrugia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!