I have a const in a library (blueprintjs).
export const Intent = {
NONE: "none" as "none",
PRIMARY: "primary" as "primary",
SUCCESS: "success" as "success",
WARNING: "warning" as "warning",
DANGER: "danger" as "danger",
};
export type Intent = typeof Intent[keyof typeof Intent];
I want to make sure that my prop which I receive from my parent only has one of the 5 key values of Intent. How do I proceed forward with this? Please advice.
This is what I have done so far.
interface Props {
exportButtonColor?: [keyof typeof Intent];
}
Any help is greatly appreciated.
Unless some very clever person has a better solution, this should work:
const Intent = {
NONE: "none" as "none",
PRIMARY: "primary" as "primary",
SUCCESS: "success" as "success",
WARNING: "warning" as "warning",
DANGER: "danger" as "danger",
};
type Intent = typeof Intent[keyof typeof Intent];
const Classes = {
INTENT_PRIMARY: "foobar",
INTENT_NONE: "barfoo",
INTENT_SUCCESS: "somecssclass",
INTENT_WARNING: "you get the idea",
INTENT_DANGER: "will robinson",
};
type IntentKey = keyof typeof Intent;
const KeyMap: {
[key in IntentKey]: keyof typeof Classes
} = {
PRIMARY: "INTENT_PRIMARY",
NONE: "INTENT_NONE",
SUCCESS: "INTENT_SUCCESS",
WARNING: "INTENT_WARNING",
DANGER: "INTENT_DANGER",
}
function test({ color }: { color: IntentKey }) {
return Classes[KeyMap[color]];
}
Notice that this is type-safety at the cost of an explicit mapping.