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

时间:2017-03-30 15:06:04

标签: typescript type-inference

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

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"'.

TextStyle@types/react0native的定义包括:

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

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

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

3 个答案:

答案 0 :(得分:4)

这应该有效:

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

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

答案 1 :(得分:1)

另一个选择是:

import { TextAlignProperty } from 'csstype'

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

答案 2 :(得分:1)

如果您使用的是Typescript 3.4+,则可以使用as const表示法:

export const locationInput = {
  textAlign: 'center' as const
};

有关更多信息,请检查documentations here