Sergej
Sergej

Reputation: 1092

Typing for key by generic type lookup

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?

Upvotes: 1

Views: 129

Answers (1)

vitoke
vitoke

Reputation: 748

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.

Upvotes: 3

Related Questions