【问题标题】:TypeScript type inference issue with string literal字符串文字的 TypeScript 类型推断问题
【发布时间】: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 问题

标签: typescript type-inference


【解决方案1】:

这应该可以工作:

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

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

【讨论】:

  • 我也可以使用text: { ... } as TextStyle,但我仍然认为编译器应该处理它。
【解决方案2】:

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

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

更多信息请查看documentations here。

【讨论】:

    【解决方案3】:

    另一个选项应该是:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多