Nisim Joseph
Nisim Joseph

Reputation: 2520

How to do Typescript compile time check to make sure 2 Enums has the same values

I need to have 2 enums with the same Keys but different values. I want to know in compile-time both have the same keys and nothing is missing or added. This is for constants I want to use.

I know I can achieve it by using Interface and create Object for both when the type is the interface I created, but this will prevent me to use const enum or just enum which has its own benefits.

For example, I want to make sure the following Enums have the same keys:

enum Enum1 {
    bar = "bar1",
    baz = "baz1",
}

enum Enum2 {
    bar = "bar2",
    baz = "baz2"
}

Upvotes: 1

Views: 352

Answers (1)

Nisim Joseph
Nisim Joseph

Reputation: 2520

I did some search and found quite a simple way to get it, with a small amount of code and with Enums of course.

All the validation check are types which will be gone in final code.

The // @ts-ignore it because I am not using the T Generic and just need it to validate it extends never which we will get when we Omit the fields of one Enum from the other and nothing is left, but when any additional field does left the value is not never so the compiler will show us error. We will do so for both enums to the other enum.

See the code here in the playground.

enum Enum1 {
    bar = "bar1",
    baz = "baz1",
}

enum Enum2 {
    bar = "bar2",
    baz = "baz2"
}

// @ts-ignore
type EnsureEnumEqual<T extends never> = true;

type OK1 = EnsureEnumEqual<keyof Omit<typeof Enum1, keyof typeof Enum2>>;
type OK2 = EnsureEnumEqual<keyof Omit<typeof Enum2, keyof typeof Enum1>>;

Upvotes: 1

Related Questions