TypeScript React Native String文字分配错误

时间:2016-06-19 22:38:42

标签: string object typescript variable-assignment literals

关于TypeScript,我遇到了一个非常奇怪的错误,告诉我字符串文字不匹配。 (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>
    );
  }
}

错误:

src\client\index.ios.tsx(19,15): error TS2322: Type '{ fontSize: number; textAlign: string; margin: number; }' is not assignable to type 'TextStyle'.
  Types of property 'textAlign' are incompatible.
    Type 'string' is not assignable to type '"auto" | "left" | "right" | "center"'.
      Type 'string' is not assignable to type '"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/

2 个答案:

答案 0 :(得分:12)

我知道我已经迟到了,但是遇到了同样的问题并且更喜欢这个解决方案(讨厌使用&#39;任何&#39;因为它有点打败了Typescript的目的,尽管有时它& #39;是唯一的选择):

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什么 type 样式来创建构建错误就解决了。

答案 1 :(得分: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