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>)}
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';
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>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With