如何从接口的属性中提取 "enum type"?

How to extract the "enum type" out of a properties from an interface?

我有一个 React 界面,例如:TextStyle。我需要使用像 textAlign 这样的动态值。但是这个文本对齐必须匹配接口枚举。我该怎么做?

我试过 typeof TextStyle["textAlign"] 但我得到了 'TextStyle' only refers to a type, but is being used as a value here.

// @see https://facebook.github.io/react-native/docs/text.html#style
export interface TextStyle extends TextStyleIOS, TextStyleAndroid, ViewStyle {
    color?: string;
    fontFamily?: string;
    fontSize?: number;
    fontStyle?: "normal" | "italic";
    /**
     * Specifies font weight. The values 'normal' and 'bold' are supported
     * for most fonts. Not all fonts have a variant for each of the numeric
     * values, in that case the closest one is chosen.
     */
    fontWeight?: "normal" | "bold" | "100" | "200" | "300" | "400" | "500" | "600" | "700" | "800" | "900";
    letterSpacing?: number;
    lineHeight?: number;
    textAlign?: "auto" | "left" | "right" | "center" | "justify";
    textDecorationLine?: "none" | "underline" | "line-through" | "underline line-through";
    textDecorationStyle?: "solid" | "double" | "dotted" | "dashed";
    textDecorationColor?: string;
    textShadowColor?: string;
    textShadowOffset?: { width: number; height: number };
    textShadowRadius?: number;
    testID?: string;
}

我想从 TextStyle 界面中提取枚举以获得 type TextAligEnum = "auto" | "left" | "right" | "center" | "justify";

例如:

const renderX = ({
  title = "title",
  textAlign = "center"
}: {
  title: string;
  textAlign?: typeof TextStyle["textAlign"];
                     ^^^^^^^^^ 'TextStyle' only refers to a type, but is being used as a value here.
}) => {
  return (
      <Text style={{ textAlign }]}>
        {title.toUpperCase()}
      </Text>

  );
};

不需要typeof,直接使用TextStyle["textAlign"]即可。

const renderX = ({
  title = "title",
  textAlign = "center"
}: {
  title: string;
  textAlign?: TextStyle["textAlign"];
}) => {
  return (
      <Text style={{ textAlign }]}>
        {title.toUpperCase()}
      </Text>

  );
};

typeof 接受一个值的标识符和 returns 它的类型。但是 TextStyle 已经是一个类型,这就是为什么它不能与 typeof.

一起使用的原因

您可以使用 TextStyle["textAlign"] 作为类型:

interface TextStyle {
    color?: string;
    fontFamily?: string;
    fontSize?: number;
    fontStyle?: "normal" | "italic";
    fontWeight?: "normal" | "bold" | "100" | "200" | "300" | "400" | "500" | "600" | "700" | "800" | "900";
    letterSpacing?: number;
    lineHeight?: number;
    textAlign?: "auto" | "left" | "right" | "center" | "justify";
    textDecorationLine?: "none" | "underline" | "line-through" | "underline line-through";
    textDecorationStyle?: "solid" | "double" | "dotted" | "dashed";
    textDecorationColor?: string;
    textShadowColor?: string;
    textShadowOffset?: { width: number; height: number };
    textShadowRadius?: number;
    testID?: string;
}


const a1: TextStyle["textAlign"] = "left"; // ok
const a2: TextStyle["textAlign"] = "center"; // ok
const a3: TextStyle["textAlign"] = "middle";  // error