确保 prop 是来自常量的值 - TS
Make sure that prop is a value from a constant - TS
我在库 (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];
我想确保我从 parent 收到的道具只有 Intent 的 5 个键值之一。我该如何进行呢?请指教
这是我目前所做的。
interface Props {
exportButtonColor?: [keyof typeof Intent];
}
非常感谢任何帮助。
除非某个非常聪明的人有更好的解决方案,否则这应该可行:
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]];
}
请注意,这是以显式映射为代价的类型安全。
我在库 (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];
我想确保我从 parent 收到的道具只有 Intent 的 5 个键值之一。我该如何进行呢?请指教
这是我目前所做的。
interface Props {
exportButtonColor?: [keyof typeof Intent];
}
非常感谢任何帮助。
除非某个非常聪明的人有更好的解决方案,否则这应该可行:
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]];
}
请注意,这是以显式映射为代价的类型安全。