在 native 应用程序中,我有这样的风格
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/react-native
包括:export interface TextStyle extends TextStyleIOS, TextStyleAndroid,
ViewStyle {
// ...
textAlign?: "auto" | "left" | "right" | "center"
// ...
}
为什么编译器会提示不兼容?好像是在推断
textAlign
的类型太笼统了string
而不是检查实际值( "center"
)。我知道我可以使用
as TextStyle
以避免这个问题,但我想知道它为什么会发生,以及我是否应该针对编译器提交一张票。
最佳答案
这应该有效:
const styles = StyleSheet.create({
text: {
textAlign: "center" as "center"
},
})
通常,TypeScript 会将 textAlign 键入为字符串,但由于它不能只是任何字符串,因此您可以将其转换为更具体的类型。
关于字符串文字的 TypeScript 类型推断问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43121661/