Partially filled generics?

Sorry about the title, I don't know what to call what I'm asking for.

I want to make a registry of type guards. I can't figure out how to do it in a way that doesn't throw casts all over the place. What I'd like to do is something like this:

const registry<T>: Map<T, (x: any) => x is T> = new Map();

and then populate it with records like

class Example {
    static guard(x): x is Example { ... }
}

registry.set(Example, Example.guard);

Is there a way to do this?

Posted Oct 8, 2017, 4:38 PM UTC

54
alsiola•

You can make a wrapper around an instance of Map which gives you the typings you want:

type Guard<T> = (x: any) => x is T;

const registry = (() => {
    const store = new Map();
    return {
        set: <T>(a: T, guard: Guard<T>) => {
            store.set(a, guard);
        },
        get: <T>(a: T): Guard<typeof a> => {
            return store.get(a);
        }
    };
})();

class ExampleA { 
    static guard = (x: any): x is typeof ExampleA => {
        return x instanceof ExampleA;
    };
}

class ExampleB {
    static guard = (x: any): x is typeof ExampleB => {
        return x instanceof ExampleB;
    };
}

registry.set(ExampleA, ExampleA.guard);

registry.set(ExampleB, ExampleB.guard);

const guardA = registry.get(ExampleA); // typed as Guard<typeof ExampleA>

const guardB = registry.get(ExampleB); // typed as Guard<typeof ExampleB>

console.log(guardA(new ExampleA())); // true
console.log(guardA(new ExampleB())); // false
console.log(guardB(new ExampleA())); // false
console.log(guardB(new ExampleB())); // true
3
ViKomprenasOP•

Ah, thanks. Although I think it should be

        set: <T>(a: typeof T, guard: Guard<T>) => {
            store.set(a, guard);
        },
        get: <T>(a: typeof T): Guard<T> => {
            return store.get(a);
        }

and

    static guard = (x: any): x is ExampleA => {
        return "exampleA" in x;
    };

shouldn't it?

Edit: Yeah, your version produces guards for things like (ExampleA & typeof ExampleA) | (ExampleB & typeof ExampleA), which are completely useless for what I'm describing. My version, meanwhile, doesn't compile.

1
alsiola•

Yeah, your version produces guards for things like (ExampleA & typeof ExampleA) | (ExampleB & typeof ExampleA), which are completely useless for what I'm describing. My version, meanwhile, doesn't compile.

I'm not sure what you mean by this

1
ViKomprenasOP•

Your version's type guards return the right results, but if you use them as type guards the type that TypeScript infers is (ExampleA & typeof ExampleA) | (ExampleB & typeof ExampleA).

1