我有一个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>
);
};
答案 0 :(得分:2)
您不需要typeof
,只需单独使用TextStyle["textAlign"]
。
const renderX = ({
title = "title",
textAlign = "center"
}: {
title: string;
textAlign?: TextStyle["textAlign"];
}) => {
return (
<Text style={{ textAlign }]}>
{title.toUpperCase()}
</Text>
);
};
typeof
接受一个值的标识符并返回其类型。但是TextStyle
已经是一种类型,这就是为什么它不能与typeof一起使用的原因。
答案 1 :(得分:1)
您可以使用a is None
作为类型:
TextStyle["textAlign"]