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

标签 typescript type-inference

在 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"'.
TextStyle的定义在 @types/react-native包括:
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 键入为字符串,但由于它不能只是任何字符串,因此您可以将其转换为更具体的类型。

关于字符串文字的 TypeScript 类型推断问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43121661/

相关文章:

javascript - Angular : Can't export excel using ExcelJS - error TS2307: Cannot find module 'stream' - error TS2503: Cannot find namespace 'NodeJS'

Angular 4全局变量设置问题

scala - higherKinds 类型别名的编译问题

javascript - 带有 React Native 的 Typescript 2.0

typescript 函数重载奇怪的行为

angular - 属性然后在类型 void 上不存在, typescript 错误

typescript - TypeScript 中柯里化(Currying)函数的类型推断

c# - 类型推断和继承

f# - F# 类型推断只能自上而下(和左右)工作吗?

java - 使用类参数时,类型绑定(bind)不是通过构造函数推断的吗?