Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript type inference issue with string literal

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.

like image 499
Ralph Avatar asked Mar 30 '17 15:03

Ralph


2 Answers

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.

like image 175
libertyernie Avatar answered Nov 25 '22 05:11

libertyernie


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.

like image 45
OM Bharatiya Avatar answered Nov 25 '22 05:11

OM Bharatiya