I have a React interface, ex: TextStyle. And I need to use a dynamic value like textAlign. But this text align has to match the interface enum. How do I do this?
I have tried typeof TextStyle["textAlign"]
but I get '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;
}
I want to extract the enum out of the TextStyle interface to have type TextAligEnum = "auto" | "left" | "right" | "center" | "justify";
For example:
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>
);
};
You don't need the typeof
, just use TextStyle["textAlign"]
by itself.
const renderX = ({
title = "title",
textAlign = "center"
}: {
title: string;
textAlign?: TextStyle["textAlign"];
}) => {
return (
<Text style={{ textAlign }]}>
{title.toUpperCase()}
</Text>
);
};
The typeof
takes an identifier of a value and returns its type. But TextStyle
is already a type, which is why it cannot be used with typeof.