Dan Zawadzki
Dan Zawadzki

Reputation: 732

Extending typescript interfaces

I have component Checkbox.tsx, which ts interface looks like:

export interface ICheckbox {
    /** DOM element id. */
    id: string;
    /** Handler to the onClick event */
    onCheck?: (e: React.ChangeEvent<HTMLInputElement>) => void;
}

Now, I would like to create another component CheckboxWithLabel.tsx, which will have a very similar interface, the only additional thing gonna be a label. How can I merge two interfaces or extends existing interface? Something like:

import {ICheckbox} from './Checkbox.tsx';

export interface ICheckboxLabel {
    ...ICheckbox,
    label: string;
}

What i have tried is:

export interface ICheckboxLabel extends ICheckbox{
     children: JSX.Element | JSX.Element[] | string;
}

The problem is, that I don't know if it's the correct approach.

Upvotes: 0

Views: 148

Answers (1)

Ammar Hussain
Ammar Hussain

Reputation: 304

You can export an interface by using extends keyword.

interface a extends b {
   ...
}

In your example it will be like.

export interface ICheckboxLabel extends ICheckbox {
   label: string
}

Also visit the official documentation for more information https://www.typescriptlang.org/docs/handbook/interfaces.html

Upvotes: 3

Related Questions