You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
TS2322: Type 'string' is not assignable to type '"absolute" | "relative" | undefined' #11465
Minimal ReactNative Component to illustrate the problem:
importReact,{Component}from'react';import{StyleSheet,Text}from'react-native';exportclassSampleextendsComponent<{},{}>{render(){return(<Textstyle={styles.text}>HelloTypeScript</Text>//erroronstyles,seebelow);}}conststyles=StyleSheet.create({text: {position: 'absolute',// cause of the error: string instead of 'absolute'top: 0,left: 0}});
Error:
error TS2322: Type '{ position: string; top: number; left: number; }' is not assignable to type 'TextStyle | undefined'.
Type '{ position: string; top: number; left: number; }' is not assignable to type 'TextStyle'.
Types of property 'position' are incompatible.
Type 'string' is not assignable to type '"absolute" | "relative" | undefined'.
I like it that the reactnative declaration doesn't use string, but only allows the set of possible strings.
Is there any way to let TypeScript infer this to type 'absolute'?
Maybe if I could mark this position field as readonly, it could infer to type 'absolute'.
I don't like casting and prevent it as much as possible, but here are workarounds:
conststyles=StyleSheet.create({text: {position: 'absolute',top: 0,left: 0}asReact.TextStyle// cast to existing interface});
When there is not interface is exported (here: TextStyle), we can cast only field:
conststyles=StyleSheet.create({text: {position: 'absolute'as'absolute',// cast string to type 'absolute'top: 0,left: 0}});
Reacted by Jamie Birch, Dipun Mistry, kraftwer1, Manu Bamba, Ivan Jiang, David Auffret, Matthew Padich, Rob Leggett, Micah Blu, Grigore Danciu and 14 more
Reacted by Andrej K, Charlie Brown, trisrael and Ivan Zakharchuk
Reacted by turenc
Reacted by Ivan Jiang, Micah Blu, adam, Dan Caddigan, Amitai Lanciano, Nattaphoom Chaipreecha, turenc and Kay Gosho
Reacted by vincent barthelemy, Amitai Lanciano, Justin Poliachik, Ben Polinsky, Nattaphoom Chaipreecha, S Kuijers, Matěj Pokorný, Larry Ruckman and Wenhan Shen
Reacted by Jose Daniel Legaspi, turenc and Kay Gosho
Activity
jovdb commentedon Oct 8, 2016
I don't like casting and prevent it as much as possible, but here are workarounds:
When there is not interface is exported (here: TextStyle), we can cast only field:
WKenya commentedon Nov 28, 2017
This is related to #19966.
matthias-ccri commentedon May 23, 2018
This can also be the case: #21618 (comment)