Recently, I developed a function to map links originating from a CMS. However, there are instances where the link in the CMS is optional. In such cases, I need to return null
. On the other hand, when the links are mandatory, having null
as a return type is not permissible. To address this, I implemented conditional types with a ternary operator and formulated the following function:
export const mapLink = <T = true>({
cached_url,
url,
target,
linktype,
...props
}: ISbLink): T extends false ? LinkProps | null : LinkProps => {
console.log({ cached_url, url, target, linktype, ...props });
if (!cached_url && !url) return null;
let href = "";
if (linktype === "url") href = url;
if (linktype === "story") href = cached_url === "home" ? "/" : cached_url;
return {
href,
target: target || "_self"
};
};
The function performs well except for an error message that states:
Type 'null' is not assignable to type 'T extends false ? InternalLinkProps | null : InternalLinkProps'
This error occurs specifically on line
if (!cached_url && !url) return null;
To see the error and how it's being used, visit the TypeScript Playground here.
If you have any suggestions on addressing this issue, please feel free to share.