在本机应用程序中,我有样式
const styles = StyleSheet.create({
text: {
textAlign: "center"
},
})
在<Text style={styles.text} />
中使用,但tsc
编译器出现以下错误:
Types of property 'textAlign' are incompatible.
Type 'string' is not assignable to type '"center" | "auto" | "left" | "right"'.
TextStyle
中@types/react0native
的定义包括:
export interface TextStyle extends TextStyleIOS, TextStyleAndroid,
ViewStyle {
// ...
textAlign?: "auto" | "left" | "right" | "center"
// ...
}
为什么编译器抱怨不兼容?它似乎推断textAlign
的类型过于笼统string
而不是检查实际值("center"
)。
我知道我可以使用as TextStyle
来避免这个问题,但我想知道它为什么会发生,以及是否应该针对编译器提交票证。
答案 0 :(得分:4)
这应该有效:
const styles = StyleSheet.create({
text: {
textAlign: "center" as "center"
},
})
通常TypeScript会将textAlign键入为字符串,但由于它不能只是任何字符串,因此可以将其强制转换为更具体的类型。
答案 1 :(得分:1)
另一个选择是:
import { TextAlignProperty } from 'csstype'
const styles = StyleSheet.create({
text: {
textAlign: "center" as TextAlignProperty
},
})
答案 2 :(得分:1)
如果您使用的是Typescript 3.4+,则可以使用as const
表示法:
export const locationInput = {
textAlign: 'center' as const
};
有关更多信息,请检查documentations here。