Johannes
Johannes

Reputation: 1329

Get base interface when extending another interface

Suppose I have this simple interface:

interface IMyButton extends Partial<HTMLInputElement> {
  color?: string
}

This allows me to extend the base HTMLInputElement with properties definied in IMyButton (e.g. for web components).

Is there a way of getting only the properties that the base type, IMyButton, defines, rather than all the properties including the ones from HTMLInputElement?

So what I need is a new type that only has color?: string as a property.

The extended interface changes from component to component, i.e. interface IMySelect extends Partial<HTMLSelectElement>, so I can't just exclude a fixed type.

Some background why I need this: I have a mapped type that uses IMyButton - so using the API you have to define defaults for example. Right now this mapped type also includes HTMLInputElement properties, that are wholly optional and don't even need defaults. Visual Studio Code for example still shows all the properties of the extended type of course, so creating this object is really difficulty because the intellisense gets cluttered with base html properties...

Upvotes: 0

Views: 177

Answers (1)

chazsolo
chazsolo

Reputation: 8439

You've pretty much already figured it out (assuming you can redefine your interfaces)

So what I need is a new type that only has color?: string as a property.

Just make an interface that has the color property, then extend both:

interface IMyButtonProps {
  color?: string
}

interface IMyButton extends IMyButtonProps, Partial<HTMLInputElement> {}

Upvotes: 1

Related Questions