Type 'string | undefined' is not assignable to type 'Url'. #54062
Replies: 2 comments 2 replies
-
Hi, In this case, I think the problem is with that, what you are trying to achieve, is not reflected in the type signatures correctly. For completeness sake, specifically, for that error message, you have to narrow out the case "a":
if (typeof props.href === "string") {
return (
<Link
href={props.href}
// {...buttonProps}
ref={ref}
// className={cvaButton({ intent, size, ...props })}
>
{children}
</Link>
);
}
return null;
// or
case "a":
if (typeof props.href !== "string") return null;
return (
<Link
href={props.href}
// {...buttonProps}
ref={ref}
// className={cvaButton({ intent, size, ...props })}
>
{children}
</Link>
);
} That's probably not fully what you want to do. I reckon, you want to make sure, that as far as the consumers of this component, are concerned, the href must be a string, when For example: import { ReactNode, useRef } from "react";
import Link from "next/link";
interface AnchorDefinition {
element: "a";
href: string;
}
interface SimpleDefinition {
element: "button" | "div";
href: never;
}
type ButtonDefinition = {
className: string;
children?: ReactNode;
} & (AnchorDefinition | SimpleDefinition);
export function Button({ element, ...props }: ButtonDefinition) {
const ref = useRef(null);
const { children } = props;
switch (element) {
case "button":
return (
<button
// {...buttonProps}
ref={ref}
// className={cvaButton({ intent, size, ...props })}
>
{children}
</button>
);
case "a":
return (
<Link
href={props.href}
// {...buttonProps}
ref={ref}
// className={cvaButton({ intent, size, ...props })}
>
{children}
</Link>
);
}
} And now, when the element is
|
Beta Was this translation helpful? Give feedback.
-
So I came across this issue. This is the solution: |
Beta Was this translation helpful? Give feedback.
-
Summary
I have created a custom component that I want to use the
Link
component inside of. In the interface for my component, I have an optionalhref
property that takes a string. When I add theLink
component, I have a type error onherf
saying:Type 'string | undefined' is not assignable to type 'Url'.
I'm not sure how to get that particular type or where it comes from. Is anyone able to illuminate me on this?
Thanks!
Additional information
Example
No response
Beta Was this translation helpful? Give feedback.
All reactions