【发布时间】:2017-08-24 14:27:59
【问题描述】:
在 react-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"'.
@types/react-native中TextStyle的定义包括:
export interface TextStyle extends TextStyleIOS, TextStyleAndroid,
ViewStyle {
// ...
textAlign?: "auto" | "left" | "right" | "center"
// ...
}
为什么编译器抱怨不兼容?似乎是在推断textAlign 的类型过于笼统的string 而不是检查实际值("center")。
我知道我可以使用as TextStyle 来避免该问题,但我想知道为什么会发生这种情况,以及是否应该向编译器提出投诉。
【问题讨论】:
-
或者可能是typings mantainer,因为看起来预期值不是字符串......
-
我认为类型维护者在限制值方面是正确的,但是编译器应该将实际值带到类型比较而不是推断
string。否则,字符串字面量类型的目的是什么? -
你确实是对的,那似乎是一个 tsc 错误.. :/
-
发现同样的问题,我曾经有这样的代码可以工作,现在已经坏了 - 认为这是 tsc 问题