字符串文字的 TypeScript 类型推断问题
TypeScript type inference issue with string literal
在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
来避免这个问题,但我想知道为什么会这样,以及我是否应该向编译器提交票证。
这应该有效:
const styles = StyleSheet.create({
text: {
textAlign: "center" as "center"
},
})
通常 TypeScript 会将 textAlign 键入为字符串,但由于它不能只是任何字符串,您可以将其转换为更具体的类型。
另一种选择是:
import { TextAlignProperty } from 'csstype'
const styles = StyleSheet.create({
text: {
textAlign: "center" as TextAlignProperty
},
})
如果您使用的是 Typescript 3.4+,则可以使用 as const
表示法:
export const locationInput = {
textAlign: 'center' as const
};
有关更多信息,请查看 documentations here。
在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
来避免这个问题,但我想知道为什么会这样,以及我是否应该向编译器提交票证。
这应该有效:
const styles = StyleSheet.create({
text: {
textAlign: "center" as "center"
},
})
通常 TypeScript 会将 textAlign 键入为字符串,但由于它不能只是任何字符串,您可以将其转换为更具体的类型。
另一种选择是:
import { TextAlignProperty } from 'csstype'
const styles = StyleSheet.create({
text: {
textAlign: "center" as TextAlignProperty
},
})
如果您使用的是 Typescript 3.4+,则可以使用 as const
表示法:
export const locationInput = {
textAlign: 'center' as const
};
有关更多信息,请查看 documentations here。