如何使两个枚举具有相同的键?
How to make two enums have the same keys?
我有这两个枚举:
enum foo {
bar,
baz
}
enum fiz {
...
}
如何确定 fiz
与 foo
具有相同的密钥?我尝试添加一个接口,但分配不成功。
你可以使用地图。
enum foo {
bar,
baz,
}
const fiz = new Map<foo, string>([
[foo.bar, 'value1'],
[foo.baz, 'value2'],
]);
或者你可以这样做
enum Foo {
A = "ActivityCode.Foo.A",
B = "ActivityCode.Foo.B",
C = "ActivityCode.Foo.C",
}
enum Bar {
A = "ActivityCode.Bar.A",
B = "ActivityCode.Bar.B",
C = "ActivityCode.Bar.C",
}
enum Baz {
A = "ActivityCode.Baz.A",
B = "ActivityCode.Baz.B",
C = "ActivityCode.Baz.C",
}
const ActivityCode = {
Foo,
Bar,
Baz,
};
console.log(ActivityCode.Foo.A);
基于,我认为这种方法适合您:
const keys = ['foo', 'bar', 'baz'] as const;
type Key = typeof keys[number]; // "foo" | "bar" | "baz"
type ObjectWithSameKeys<ValueType> = Record<Key, ValueType>;
const labels: ObjectWithSameKeys<number> = {
foo: 1,
bar: 2,
baz: 3,
};
const names: ObjectWithSameKeys<string> = {
foo: 'one',
bar: 'two',
baz: 'three',
};
我有这两个枚举:
enum foo {
bar,
baz
}
enum fiz {
...
}
如何确定 fiz
与 foo
具有相同的密钥?我尝试添加一个接口,但分配不成功。
你可以使用地图。
enum foo {
bar,
baz,
}
const fiz = new Map<foo, string>([
[foo.bar, 'value1'],
[foo.baz, 'value2'],
]);
或者你可以这样做
enum Foo {
A = "ActivityCode.Foo.A",
B = "ActivityCode.Foo.B",
C = "ActivityCode.Foo.C",
}
enum Bar {
A = "ActivityCode.Bar.A",
B = "ActivityCode.Bar.B",
C = "ActivityCode.Bar.C",
}
enum Baz {
A = "ActivityCode.Baz.A",
B = "ActivityCode.Baz.B",
C = "ActivityCode.Baz.C",
}
const ActivityCode = {
Foo,
Bar,
Baz,
};
console.log(ActivityCode.Foo.A);
基于
const keys = ['foo', 'bar', 'baz'] as const;
type Key = typeof keys[number]; // "foo" | "bar" | "baz"
type ObjectWithSameKeys<ValueType> = Record<Key, ValueType>;
const labels: ObjectWithSameKeys<number> = {
foo: 1,
bar: 2,
baz: 3,
};
const names: ObjectWithSameKeys<string> = {
foo: 'one',
bar: 'two',
baz: 'three',
};