I want to make a "semi-customized" button. Basically, I want it to extend the <button>
tag's initial properties. Here's a minimal example of what I am doing:
export default class Button extends React.Component<Props, State> {
public render() {
const { size, ...buttonProps } = this.props;
return (
<button
{...buttonProps}
className={classnames({
[styles.small]: size === 'small',
[styles.medium]: size === 'medium',
[styles.large]: size === 'large',
})}
/>
);
}
}
However, what I can't figure out is how to create an interface which inherits all of the native HTMLButton's proptypes.
I imagine it would be something like:
interface Props extends <(Something)> {
size: 'small' | 'medium' | 'large',
}
How would you extend native HTML element properties in typescript?
You can use HTMLProps
interface from react.
import { HTMLProps } from 'react'
interface Props extends HTMLProps<HTMLButtonElement> {
size: 'small' | 'medium' | 'large'
}
Interfaces in TypeScript are open and multiple declarations within the same common root are merged. Example:
interface HTMLButtonElement {
customThing(): string;
}
const button = document.getElementsByTagName('button')[0];
const customValue = button.customThing();
The HTMLButtonElement
interface needs to be declared in the same common root as the original interface (ie it is in the global scope). Once you add your customThing
, your HTMLButtonElement
will have all the members of the original HTMLButtonElement
and your customThing
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.