2

Not sure what typescript feature I am after, but I think I need a generic generic (if that is a typescript feature). Below is my requirement.

I want to represent a collection of events / event handler tuples. Below is what I have so far.

interface Event {
 type: string;
}

type EventType<T extends Event> = T['type'];
type EventHandler<T extends Event> = (event:T): void;

// so far so good
type EventTypeAndHandlerTuple <T extends Event> = [EventType<T>, EventHandler<T>];


// this is where I wish I could do better. I am forced to used any
type EventTypeAndHandlerTuples = EventTypeAndHandlerTuple<any>[]

my hopes is to be able to represent code like this

const todoAddedEvent: TodoAddedEvent = {...}
const handleTodoAddedEvent: TodoAddedHandler = (event: TodoAddedEvent) => {...};
const todoRemovedEvent: TodoRemovedEvent = {...}
const handleTodoRemovedEvent: TodoRemovedHandler = (event: TodoRemovedEvent) => {...}

// HELP ME GIVE THIS THING A TYPE 😢
const eventTypeToHandlerTuples = [
 [todoAddedEvent, handleTodoAddedEvent],
 [todoRemovedEvent, handleTodoRemovedEvent]
];

I want a type for eventTypeToHandlerTuples such that it passes if it is a collection of associated event types and event handler tuples. I want this type to signify a failure if an event type was associated with an incorrect handler. For example, I would like this to fail

// this should fail because the removed event is being paired with the add event handler.
const eventTypeToHandlerTuples = [
 [todoRemovedEvent, handleTodoAddedEvent], 
];

Cheers and thanks in advance for your input

1 Answer 1

3

The easy way to do this would be to collect a union of all Event types you care about; this might be possible since you apparently want their type properties to be unique string literal types, which could be used to discriminate such a union. If so, you define the union:

type Events = TodoAddedEvent | TodoRemovedEvent;

And then use it to describe the union of all possible EventTypeAndHandlerTuple<T> types for each element T in the Events union using some union-building technique like distributive conditional types:

type UnionOfEventTypeAndHandlerTuples = Events extends infer T ?
  T extends Event ? EventTypeAndHandlerTuple<T> : never : never;
// type UnionOfEventTypeAndHandlerTuples = 
// EventTypeAndHandlerTuple<TodoAddedEvent> | EventTypeAndHandlerTuple<TodoRemovedEvent>

Once you have this, the type you want is just UnionOfEventTypeAndHandlerTuples[]:

// okay
const eventTypeToHandlerTuples: UnionOfEventTypeAndHandlerTuples[] = [
  [todoAddedEvent, handleTodoAddedEvent],
  [todoRemovedEvent, handleTodoRemovedEvent]
];

// error
const badEventTypeToHandlerTuples: UnionOfEventTypeAndHandlerTuples[] = [
  [todoRemovedEvent, handleTodoAddedEvent], // error!
];

If you don't have a predefined union, then things become more difficult. Without something like native support for existential generic types in TypeScript (see microsoft/TypeScript#14466), there's no specific type like EventTypeAndHandlerTuple<exists T extends Event>[] where exists T means "I don't know or care what T is, I just care that it exists". You could think of existential types as an "infinite union" of all possible matching types.

Instead you need to do something else. Probably the most reasonable for TypeScript is to use the regular old generic types in TypeScript (these are called universal instead of existential and act like "infinite intersections" instead of "infinite unions"), and use a helper function to make the compiler infer the generic for you so you don't have to write it out:

const asEventTypeToHandlerTuples = <T extends Event[]>(
  tuples: [...{ [I in keyof T]: EventTypeAndHandlerTuple<Extract<T[I], Event>> }]
) => tuples;

The helper function asEventTypeToHandlerTuples() accepts a single parameter named tuples and returns it. The type of this argument is constrained to be a mapped tuple type where it turns an array of Event types into the corresponding array of EventTypeAndHandlerTuple types. If the type of T is inferred to be [TodoAddedEvent, TodoRemovedEvent, SomeOtherEvent], then the type of tuples() is constrained to be [EventTypeAndHandlerTuple<TodoAddedEvent>, EventTypeAndHandlerTuple<TodoRemovedEvent>, EventTypeAndHandlerTuple<SomeOtherEvent>]. Let's see how it works. We no longer annotate the types of our variables, but instead let the compiler infer them:

// okay
const eventTypeToHandlerTuples = asEventTypeToHandlerTuples([
  [todoAddedEvent, handleTodoAddedEvent],
  [todoRemovedEvent, handleTodoRemovedEvent]
]);

// error
const badEventTypeToHandlerTuples = asEventTypeToHandlerTuples([
  [todoRemovedEvent, handleTodoAddedEvent], // error!
]);

The eventTypeToHandlerTuples assignment works with no problem, but badEventTypeToHandlerTuples gives an error because it inferred its type to be [EventTypeAndHandlerTuple<TodoAddedEvent>], but todoRemovedEvent is not assignable to EventType<TodoAddedEvent>, and you get the desired error.


Personally I'd try to use an Events-like union because it's a lot easier to deal with unions of specific types than it is to drag generic type parameters around with your code base to represent your constraints. But if that is not feasible, generic helper functions are often an acceptable substitute for the kind of unrepresentable existential types you're looking for.

Playground link to code

4
  • Thank you so much for your answer. It really did help. Would you have an opinion on what should be done if I am creating a function that anticipates a tuple as a parameter?
    – alaboudi
    Feb 15, 2021 at 23:23
  • I don't quite understand the question... is this related to the code here or is it a separate question? A minimal reproducible example code sample would be helpful
    – jcalz
    Feb 16, 2021 at 1:20
  • I am trying to create a utility function in an npm module that will take in the tuples. As a library, I don't necessarily know the [event, eventHandler] tuples the user will be providing. I was hoping to be able to provider the consuming developer feedback if the tuples don't pass the type check.
    – alaboudi
    Feb 16, 2021 at 19:22
  • Then give the utility function a generic signature like the asEventTypeToHandlerTuples() function above.
    – jcalz
    Feb 16, 2021 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.