TypeScript Real Source Assignment Error

I got a very strange error regarding TypeScript saying that string literals do not match. (TypeScript v1.8)

import { Component } from "react"; import { StyleSheet, Text, View } from "react-native"; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: "#F5FCFF", }, welcome: { fontSize: 20, textAlign: "center", margin: 10, } }); export class App extends Component<any, any> { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> </View> ); } } 

Error: src \ client \ index.ios.tsx (19,15): error TS2322: Enter '{fontSize: number; textAlign: string; margin: number; } 'is not assigned to type TextStyle. TextAlign property types are incompatible. The type 'string' is not assigned to the type '' auto ''. "left" | "right" | "Centre" '. The type 'string' is not assigned to the type '' center ''.

I installed the correct vise. The following does not seem to work in TypeScript.

 interface Test { a: "p" | "q" } let x : Test; let y = { a: "p" } x = y; 

Source: https://blog.lopezjuri.com/2015/12/30/react-native--typescript/

+6
source share
2 answers

I know that I am late for the game, but I came across the same problem and preferred this solution (I hate using "any", as this partly affects the purpose of Typescript, although sometimes this is the only option):

 import { Component } from "react"; import { StyleSheet, Text, View } from "react-native"; interface Props { } interface State { } interface Style { container: React.ViewStyle, welcome: React.TextStyle } const styles = StyleSheet.create<Style>({ container: { flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: "#F5FCFF", }, welcome: { fontSize: 20, textAlign: "center", margin: 10, } }); export class App extends Component<Props, State> { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> </View> ); } } 

If we say StyleSheet.create, the style type for creating the build error will be allowed.

+12
source

Unfortunately, you need to confirm the type:

 <Text style={styles.welcome as any}> 

Cause:

The type is inferred based on declaraiton. A string literal is output as string (instead of a string literal) because

 let foo = "asdf"; // foo: string // Its a string becuase: foo = "something else"; // Would be strange if this would error 
+5
source

All Articles