TypeScript React Native String 文字赋值错误
Posted
技术标签:
【中文标题】TypeScript React Native String 文字赋值错误【英文标题】:TypeScript React Native String literal assignment error 【发布时间】:2016-10-21 02:52:52 【问题描述】:关于 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/
【问题讨论】:
Typescript 2.1.x 也有这个问题。 【参考方案1】:遗憾的是你需要断言类型:
<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
【讨论】:
【参考方案2】:我知道我迟到了,但只是遇到了同样的问题并且更喜欢这个解决方案(讨厌使用 '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 什么type 样式来创建构建错误就解决了。
【讨论】:
我发现在 "container: ... " 定义之后添加 "as React.ViewStyle 更简单、更简洁,就在将它与欢迎定义分开的逗号之前。然后添加 "as React.TextStyle" 遵循 "welcome : ... " 定义。这样,如果其他人去添加新文件,则需要添加类型的样式将是显而易见的。以上是关于TypeScript React Native String 文字赋值错误的主要内容,如果未能解决你的问题,请参考以下文章
[React Native] Up & Running with React Native & TypeScript
React-native:从 javascript 迁移到 typescript
已有的react-native 项目配置TypeScript
在后端、react 和 react-native 客户端之间共享 typescript 代码