Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript generic enum validation guard not returning the type of the enum

I’m having trouble creating a validation guard for enums. The enum guard function I created does fine with checking that the value passed into the function actually exists in the enum object, but I can’t seem to get the return type to be set to the type of the enum.

For reference here are all of my validation guards so you can see what this looks like.

export const UNDEFINED = (x: unknown): x is undefined => Object.prototype.toString.call(x) === '[object Undefined]';
export const NULL = (x: unknown): x is null => Object.prototype.toString.call(x) === '[object Null]';
export const STRING = (x: unknown): x is string => Object.prototype.toString.call(x) === '[object String]'
export const NUMBER = (x: unknown): x is number => Object.prototype.toString.call(x) === '[object Number]'
export const BOOLEAN = (x: unknown): x is boolean => Object.prototype.toString.call(x) === '[object Boolean]'

export type Guard<T> = (x: unknown) => x is T;
export type Guarded<T extends Guard<unknown>> = T extends Guard<infer V> ? V : never;

export const OBJECT =
    <T extends object>(propGuardObj: { [K in keyof T]: Guard<T[K]> }) =>
        (x: any): x is T =>
            Object.prototype.toString.call(x) === '[object Object]' &&
            (Object.keys(propGuardObj) as Array<keyof T>).every(k => (k in x) && propGuardObj[k](x[k]));
export const ARRAY =
    <T>(elemGuard: Guard<T>) =>
        (x: unknown): x is Array<T> =>
            Array.isArray(x) &&
            x.every(el => elemGuard(el));
export const OR =
    <T1, T2>(guard1: Guard<T1>, guard2: Guard<T2>) =>
        (x: unknown): x is T1 | T2 =>
            guard1(x) || guard2(x);
export const AND =
    <T1, T2>(guard1: Guard<T1>, guard2: Guard<T2>) =>
        (x: unknown): x is T1 & T2 =>
            guard1(x) && guard2(x);

// There's a problem with the 'ENUM' type guard
export const ENUM = 
    <T extends object>(e: T) => 
        (x: unknown): x is T =>
            (Object.keys(e) as Array<keyof T>)
                .filter(n => isNaN(Number(n)))
                .some(k => e[k] === x)

All of the other validation guards work as intended, namely they check the value supplied and if the function returns true then the values type is set correctly. However with the ENUM guard rather than the values type being set to just simply T the type gets set to typeof T

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s an example of what’s happening.

enum MyStringEnum { a = 'a', b = 'b', c = 'c' }

let val: any = 'a'

if (ENUM(MyStringEnum)(val)) {
    // I get a compile error [Type 'typeof MyStringEnum' is not assignable to type 'MyStringEnum']
    // I'm expecting that after the validation guard the 'val' variable will have a type of 'MyStringEnum'
    let val2: MyStringEnum = val
}

Any help is appreciated.

Update

If I try to create the enum validation guard without generics then I can get it to work by writing it like this, but I’d like for the enum validation guard to be generic for T rather than specific to MyStringEnum:

export const ENUM2 = 
    (e: typeof MyStringEnum) =>                                  // had to write "typeof MyStringEnum" here
        (x: unknown): x is MyStringEnum =>
            (Object.keys(e) as Array<keyof typeof MyStringEnum>) // had to write "typeof MyStringEnum" here
                .filter(n => isNaN(Number(n)))
                .some(k => e[k] === x)

>Solution :

It can possibly be cleaned up and generalized, but you could try something like this.

export const ENUM = 
    <T extends Record<string, string>>(e: T) => 
        (x: unknown): x is T[keyof T] =>
            (Object.keys(e) as Array<keyof T>)
                .filter(n => isNaN(Number(n)))
                .some(k => e[k] === x)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading