TypeScript TS2339 when extracting URL string from string | URL | Request
In an Expo React Native app, I accept a parameter that can be a string, URL, or Request.
function toUrlString(url: string | URL | Request) {
if (typeof url === "string") return url;
if (url instanceof URL) return url.href;
return url.url; // Request case
}
TypeScript reports:
TS2339: Property 'url' does not exist on type 'string | URL | Request'
Property 'url' does not exist on type 'URL'
In this case, when the value is a Request, I want to extract the request URL as a string using the Fetch API’s Request.url property.
What is the correct type-safe way to narrow this union so that each case (string, URL, and Request) is handled explicitly without using type assertions?