To enforce a generic type parameter to be an enum, you can use TypeScript's conditional types and the keyof operator to restrict the generic type to only accept enum types.

Here's how you can achieve this:

enum ExampleEnum { Value1 = 'VALUE1', Value2 = 'VALUE2', Value3 = 'VALUE3', } // Define a type that checks if T is an enum type type IsEnum<T> = T extends Record<infer Key, infer Value> ? Key extends keyof typeof T ? Value extends string | number ? T : never : never : never; // Define your function with the generic type constrained to an enum function doSomethingWithEnum<T extends IsEnum<T>>(value: T): void { // Your function logic here } // Usage doSomethingWithEnum(ExampleEnum.Value1); // Valid doSomethingWithEnum('invalid'); // Error: Argument of type '"invalid"' is not assignable to parameter of type 'ExampleEnum' doSomethingWithEnum(42); // Error: Argument of type '42' is not assignable to parameter of type 'ExampleEnum'

In this example, we define a type IsEnum<T> that checks if the provided type T is an enum. The type uses conditional types to ensure that T is an object with key-value pairs, and the values are either strings or numbers (typical for TypeScript enums). If the condition is met, it returns T, otherwise, it returns never.

Then, we use this IsEnum<T> type to constrain the generic type T in the doSomethingWithEnum function. Now, the function only accepts enum types as its argument, and any other types will result in a compilation error.

By using this approach, you can enforce that a generic type parameter must be an enum and prevent misuse of the function with other types.

Have questions or queries?
Get in Touch