Home > front end >  Typing for key by generic type lookup
Typing for key by generic type lookup

Time:09-17

I'm trying to get strong typings like this:

enum Schema {
  content = 'content',
  interaction = 'interaction',
}

type ContentData = {
  content: string;
};

type Data = Record<Schema, unknown> & {
  [Schema.content]: ContentData;
}

type Event<T extends keyof typeof Schema> = {
  event: string;
  schema: T;
  data: Data[T] // <----- error: Type 'T' cannot be used to index type 'Data'.
};

My issue now is, I would like to type data depending on the schema selected, but TS throws an error Type 'T' cannot be used to index type 'Data'..

The expected behavior would be:

Event<Schema.content> === {
  event: string;
  schema: Schema.content;
  data: ContentData;
}

Event<Schema.interaction> === {
  event: string;
  schema: Schema.interaction;
  data: unknown;
}

How can I achive this?

CodePudding user response:

You are treating an enum like it's an object, but it's a proper type. So if you instead use:

type Event<T extends Schema> = {
  event: string;
  schema: T;
  data: Data[T];
}

Then it should just work.

  • Related