Home > Enterprise >  Check value in type
Check value in type

Time:08-13

I have an icon component that takes a certain variant of an icon name and returns the result.

<Icon variant="add" />

I get possible component types like this

type IconProps = React.ComponentProps<typeof Icon>;
// IconProps["variant"] = "add"| "remove" | "plus" | "minus"

How do I check the name of an icon in a component? For example:

<Icon variant={"download" in IconProps["variant"] ? "download" : "add"} />

CodePudding user response:

Alternatively, you could do something like this:

IconProps["variant"] === "download" ? <Icon variant="download" /> : <Icon variant="add" /> 

CodePudding user response:

Unfortunately, type information cannot be used in actual code. It is removed during transpilation, and therefore unavailable at runtime.

So as you figured out, we cannot use the type IconProps["variant"] to dynamically select between 2 actual string values.

If there is no possibility to access/modify Icon code to get the available actual values, then we can only rely on TypeScript in IDE and compiler to warn about type mismatch.

  • Related