Hello,
I'm trying to create a getLink React HOC that returns:
- an
"a"intrinsic element ifisExternalprop istrue - a component taken from its argument (polymorphic) if
isExternalisfalse
A basic JS implementation would be like this:
export const getLink = (LinkImpl) => {
const Link = forwardRef((props, ref) => {
const { isExternal, noFollow, ...rest } = props;
const wrapperProps = {
rel: noFollow ? "nofollow" : undefined,
target: isExternal ? "_blank" : undefined,
...rest,
};
if (isExternal) {
return <a {...wrapperProps} ref={ref} />;
}
return <LinkImpl {...wrapperProps} ref={ref} />;
});
Link.displayName = "Link";
return Link;
};
I'm struggling to find a way to correctly type this in TS.
What I've come up with so far:
https://tsplay.dev/w8Dvdw
The types seems to be working somewhat but there are some issues:
Type 'UrlObject' is not assignable to type 'string'.on the return statement (line 41).
Is it safe to assume that this error can be ignored as thehrefprop is inherited from theLinkImplcomponent and thus they should match in any case?- I manually casted two variables with an
as(line 27 and 32) statement althoughpropsis of typeLinkPropsand should contain all the referenced properties in any case.
What is the best way to refactor the code to avoid those issues?
The returned component props type should:
- Expose all implementation component props
- Add
noFollowandisExternalboolean props - Force
hrefto bestringwhenisExternalistrue
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.