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

Ral*_*lph 1 type-inference typescript

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

const styles = StyleSheet.create({
    text: {
        textAlign: "center"
    },
})
Run Code Online (Sandbox Code Playgroud)

在中使用<Text style={styles.text} />,但tsc编译器给出以下错误:

Types of property 'textAlign' are incompatible.
Type 'string' is not assignable to type '"center" | "auto" | "left" | "right"'.
Run Code Online (Sandbox Code Playgroud)

TextStylein 的定义@types/react-native包括:

export interface TextStyle extends TextStyleIOS, TextStyleAndroid, 
ViewStyle {
    // ...
    textAlign?: "auto" | "left" | "right" | "center"
    // ...
}
Run Code Online (Sandbox Code Playgroud)

为什么编译器抱怨不兼容?似乎是在推断类型textAlign过于笼统,string而不是检查实际值("center")。

我知道我可以使用a as TextStyle来避免该问题,但是我想知道为什么会发生这种情况以及是否应该向编译器提交故障单。

Ger*_*hat 6

另一种选择是:

import { TextAlignProperty } from 'csstype'

const styles = StyleSheet.create({
    text: {
        textAlign: "center" as TextAlignProperty
    },
})
Run Code Online (Sandbox Code Playgroud)


lib*_*nie 5

这应该起作用:

const styles = StyleSheet.create({
    text: {
        textAlign: "center" as "center"
    },
})
Run Code Online (Sandbox Code Playgroud)

通常,TypeScript会将textAlign输入为字符串,但是由于它不能只是任何字符串,因此可以将其强制转换为更特定的类型。


OM *_*iya 5

如果您使用的是 Typescript 3.4+,则可以使用以下as const符号:

export const locationInput = {
  textAlign: 'center' as const
};
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请在此处查看文档