cal*_*via 6 string object literals variable-assignment typescript
关于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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
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"'.
Run Code Online (Sandbox Code Playgroud)
我安装了正确的打字机.似乎以下在TypeScript中不起作用.
interface Test {
a: "p" | "q"
}
let x : Test;
let y = {
a: "p"
}
x = y;
Run Code Online (Sandbox Code Playgroud)
资料来源:https://blog.lopezjuri.com/2015/12/30/react-native--typescript/
Cai*_*len 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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我们告诉StyleSheet.create要解决什么类型的样式来创建构建错误.
遗憾的是你需要断言类型:
<Text style={styles.welcome as any}>
Run Code Online (Sandbox Code Playgroud)
原因:
该类型基于declaraiton推断.字符串文字被推断为string(而不是字符串文字)因为
let foo = "asdf"; // foo: string
// Its a string becuase:
foo = "something else"; // Would be strange if this would error
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4117 次 |
| 最近记录: |