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
You can make a wrapper around an instance of Map which gives you the typings you want:
Ah, thanks. Although I think it should be
and
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.I'm not sure what you mean by this
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).