2016-06-19 40 views
6

我一直在得到一个关于TypeScript的非常奇怪的错误,告诉我字符串文字不匹配。 (打字稿V1.8)TypeScript React本机字符串文字赋值错误

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> 
    ); 
    } 
} 

错误: SRC \客户\ index.ios.tsx(19,15):错误TS2322:类型“{fontSize的:号码; textAlign:string;保证金:数量; }'不可分配为键入'TextStyle'。 属性'textAlign'的类型不兼容。 类型'字符串'不可分配为''auto'| “离开”| “正确”| “中央”'。 类型'字符串'不可分配为键入''center''。

我安装了正确的类型。看来下面的代码在TypeScript中不起作用。

interface Test { 
    a: "p" | "q" 
} 

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

x = y; 

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

+0

我也有Typecript 2.1.x的这个问题。 – Learner

回答

5

可悲的是,你需要断言类型:

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

原因:

类型推断基于declaraiton。字符串文字被推断为string(而不是字符串文字),因为

let foo = "asdf"; // foo: string 

// Its a string becuase: 
foo = "something else"; // Would be strange if this would error 
12

我知道我迟到了比赛,但对面的同样的问题来了,更喜欢这种解决方案(讨厌使用“任意”,因为它那种失败打字稿的目的,虽然有时它是唯一的选择):

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> 
    ); 
    } 
} 

如果我们告诉StyleSheet.create什么类型的样式创建生成错误得到解决。

+3

我发现在“container:{...}”定义之后添加“作为React.ViewStyle,在逗号分隔它与欢迎定义之前,它更容易和更干净”,然后将“作为React.TextStyle”添加到“欢迎:{...}“的定义。 这样,如果别人去添加新文件,需要添加输入的样式会很明显。 –