TypeScript字符串字面量推断问题

13
在一个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来避免这个问题,但我想知道为什么会发生这种情况,以及是否应该向编译器提交错误报告。

或许应该联系类型维护者,因为预期的值似乎不是一个字符串... - Paolo Casciello
我认为 typings 维护者在限制值方面是正确的,但编译器应该将实际值传递到类型比较中,而不是推断为 string。否则,拥有字符串字面类型的目的是什么? - Ralph
你说得对,看起来是一个tsc错误.. :/ - Paolo Casciello
找到相同的问题,我以前有一个像这样工作的代码,现在却出了问题 - 我认为是tsc的问题。 - SDK
4个回答

23

如果您正在使用Typescript 3.4+,您可以使用as const标记:

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

要获取更多信息,请查看这里的文档


21

这应该可以工作:

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

通常,TypeScript会将textAlign类型定义为字符串类型,但由于它不仅仅是任意的字符串,因此您可以将其强制转换为更具体的类型。


1
我也可以使用 text: { ... } as TextStyle,但我仍然认为编译器应该处理它。 - Ralph

6

另一种选择是:

import { TextAlignProperty } from 'csstype'

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

谢谢您提供的解决方案,这正是我所需要的! :) - DarkAngel

1

我想在React TypeScript中做类似的事情,这里的答案接近但并不是完全可行的解决方案。相反,我发现我必须从csstype导入Property,然后将其转换为Property.TextAlign。

在下面的示例中,我调用一个函数,该函数返回Property.TextAlign而不是常规字符串。

import { Property } from 'csstype'

...

const getTextAlign = (dataType: string):Property.TextAlign => {
    var output:string = "left";

    if(dataType === "Money"){
        output = "right";
    }

    return output as Property.TextAlign;
}

...

<td style={{textAlign: getTextAlign(this.state.dataType) }}>

尝试跟随其他解决方案,我遇到了一个错误,即 csstype 中未定义 TextAlignProperty。 在这里,我特别在一个 PCF 控件中工作,但这并不重要。这可能是由于 React 的版本差异引起的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接