I’ve got a <Button />
component which can take several props fullWidth
, iconName
and iconPosition
which as the name suggests would render an icon in the button. I made a base type which extends the native HTML button and added fullWidth: string
. This type is then extended twice to cover the icon cases adding iconPosition: 'icon-left' | 'icon-right' | 'icon-only'
and iconName: string
, and when iconPosition = 'icon-only'
I remove the children
prop and then have the aria-label
prop as required. I made a code sandbox which can be viewed here
The problem is my first attempt of just extending the base type didn’t work as expected as I could satisfy the types by only passing iconPosition: 'icon-only'
aria-label: 'something'
which is wrong as it should also show me a type error that iconName
is missing.
In my second attempt I don’t extend the base type and instead use unions and intersections so that the type reads as “the props will be of base type and then could also be one of the icon types”. This works better than attempt one but when it comes to passing children
to a button with icon-only
instead of the type error saying “children
does not exist on type..” it says “Type ‘”icon-only”‘ is not assignable to type ‘undefined'” which is not helpful.
Is there a better way to achieve what I’m trying to do or am I missing something here?