In a react-native application, I have the style
const styles = StyleSheet.create({
text: {
textAlign: "center"
},
})
used in <Text style={styles.text} />
, but the tsc
compiler gives the following error:
Types of property 'textAlign' are incompatible.
Type 'string' is not assignable to type '"center" | "auto" | "left" | "right"'.
The definition of TextStyle
in @types/react-native
includes:
export interface TextStyle extends TextStyleIOS, TextStyleAndroid,
ViewStyle {
// ...
textAlign?: "auto" | "left" | "right" | "center"
// ...
}
Why is the compiler complaining about incompatibility? It seems that it is inferring the type of textAlign
to be the too general string
instead of checking the actual value ("center"
).
I know that I can use a as TextStyle
to avoid the problem, but I would like to know why it is happening and if I should file a ticket against the compiler.
This ought to work:
const styles = StyleSheet.create({
text: {
textAlign: "center" as "center"
},
})
Normally TypeScript would type textAlign as string, but since it can't just be any string, you can cast it to the more specific type.
If you're using Typescript 3.4+ you can make use of the as const
notation:
export const locationInput = {
textAlign: 'center' as const
};
For more info check documentations here.
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