TypeScript React Native String文字分配错误

问题描述 投票:6回答:2

关于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/

string object typescript variable-assignment literals
2个回答
12
投票

我知道我已经迟到了游戏,但只是遇到了同样的问题而更喜欢这个解决方案(讨厌使用'any',因为它有点打败了Typescript的目的,虽然有时它是唯一的选择):

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要解决什么类型的样式来创建构建错误。


5
投票

遗憾的是你需要断言类型:

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

原因:

根据声明推断出类型。字符串文字被推断为string(而不是字符串文字)因为

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

// Its a string becuase: 
foo = "something else"; // Would be strange if this would error
© www.soinside.com 2019 - 2024. All rights reserved.