在反应本机应用程序中,我有这样的风格
const styles = StyleSheet.create({
text: {
textAlign: "center"
},
})
used in <Text style={styles.text} />
,但是tsc
编译器给出以下错误:
Types of property 'textAlign' are incompatible.
Type 'string' is not assignable to type '"center" | "auto" | "left" | "right"'.
的定义TextStyle
in @types/react-native
包括:
export interface TextStyle extends TextStyleIOS, TextStyleAndroid,
ViewStyle {
// ...
textAlign?: "auto" | "left" | "right" | "center"
// ...
}
为什么编译器会抱怨不兼容?看起来它正在推断类型textAlign
过于笼统string
而不是检查实际值("center"
).
我知道我可以使用as TextStyle
为了避免这个问题,但我想知道为什么会发生这种情况,以及我是否应该向编译器提交票据。
如果您使用的是 Typescript 3.4+,您可以使用as const
符号:
export const locationInput = {
textAlign: 'center' as const
};
欲了解更多信息,请检查文档在这里 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)