字符串文字的 TypeScript 类型推断问题

问题描述:

在本机应用程序中,我有样式

In a react-native application, I have the style

const styles = StyleSheet.create({
    text: {
        textAlign: "center"
    },
})

用于<Text style={styles.text}/>,但是tsc编译器报错如下:

used in <Text style={styles.text} />, but the tsc compiler gives the following error:

Types of property 'textAlign' are incompatible.
Type 'string' is not assignable to type '"center" | "auto" | "left" | "right"'.

@types/react-nativeTextStyle的定义包括:

export interface TextStyle extends TextStyleIOS, TextStyleAndroid, 
ViewStyle {
    // ...
    textAlign?: "auto" | "left" | "right" | "center"
    // ...
}

为什么编译器会抱怨不兼容?似乎是将 textAlign 的类型推断为过于通用的 string 而不是检查实际值 ("center").

Why is the compiler complaining about incompatibility? It seems that it is inferring the type of textAlign to be the too general string instead of checking the actual value ("center").

我知道我可以使用 as TextStyle 来避免这个问题,但我想知道它为什么会发生,以及我是否应该向编译器提交一张票.

I know that I can use a as TextStyle to avoid the problem, but I would like to know why it is happening and if I should file a ticket against the compiler.

这应该有效:

const styles = StyleSheet.create({
    text: {
        textAlign: "center" as "center"
    },
})

通常,TypeScript 会将 textAlign 输入为字符串,但由于它不能只是任何字符串,因此您可以将其转换为更具体的类型.

Normally TypeScript would type textAlign as string, but since it can't just be any string, you can cast it to the more specific type.