我可以使用typescript将对象键限制为枚举值吗?

时间:2017-02-10 21:39:47

标签: generics typescript enums typescript-generics

基本上,我想要一种方法来确保options参数具有键,这些键是特定枚举的值:

//enum Mode { Foo, Bar };
interface Mode { Foo: number, Bar: number }

interface View { 
    text: string;
};

class FooView implements View {
    text = 'foo';
 }

class BarView implements View { 
    text = 'bar';
}

function initialize(options: { mode: {[P in keyof Mode]?: View} }) {
    let mode: View = options.mode.Foo;
}

initialize({ mode: { Bar: new FooView() } });

如果我使用接口/类而不是枚举,它的效果非常好,但这确实是一个枚举(从概念上讲)......

请参阅this playground

1 个答案:

答案 0 :(得分:0)

键必须是字符串或数字。您可以这样做,但您必须使用括号语法并将对象的键设置为数字:

enum Mode { Foo, Bar };

function initialize(options: { mode: {[key:number]: View} }) {
    let mode: View = options.mode[Mode.Foo];
}

initialize({ mode: { [Mode.Bar]: new FooView() } });

这个答案的想法来自Sohneeanswer to a similar question

显然,这里需要注意的是,某人可以像

一样轻松做事
initialize({ mode: { [999]: new FooView() } });

不太理想。如果值不是有效模式,那么你可以做的最好的事情是在运行时抛出错误:

if (!Object.keys(options.mode).every((key) => key in Mode)) {
    throw new Error("Nice try");
}