0

我在库(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];

我想确保我从父母那里收到的道具仅具有 Intent 的 5 个关键值之一。我该如何继续进行呢?请指教。

这是我到目前为止所做的。

interface Props {
  exportButtonColor?: [keyof typeof Intent];
}

任何帮助是极大的赞赏。

4

1 回答 1

1

除非某个非常聪明的人有更好的解决方案,否则这应该有效:

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]];
}

请注意,这是以显式映射为代价的类型安全。

操场

于 2020-03-20T17:09:49.717 回答