jcubic
jcubic

Reputation: 66590

Generic interface extending parameterized interface in TypeScript

I have types like this where I overwrite single type while extending interface:

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

interface HTMLEvent<T> extends Omit<Event, 'target'> {
    target: T;
}

and now I want to create type EventType that will accept Event type for instance MouseEvent and target type.

I've tried this:

interface EventType<E, T> extends Omit<E, 'target'> {
    target: T;
}

const e: EventType<MouseEvent, HTMLButtonElement>;

but got error:

An interface can only extend an object type or intersection of object types with statically known members.

I think what I need is a function that will create a type.

Is interface EventType possible in TypeScript? Is it possible to have one generic type without the need to specify generic interface for each event type.

Upvotes: 2

Views: 1735

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250186

The error is pretty clear about the restrictions placed on interface inheritance. Since the type contains an unresolved type parameter, Typescript will not let you use it in the extends clause of the interface.

You can get a similar effect using an intersection type instead :

type EventType<E extends Event, T> = Omit<E, 'target'> &  {
    target: T;
}

Upvotes: 3

Related Questions