TypeScript中如何结合URL对象使用Fetch API?WebStorm类型问题求解
Great question! Let’s break down why this happens and how to fix it without relying on type assertions.
First, the core issue: In the older lib.dom.d.ts bundled with WebStorm 181.4445.29 (corresponding to WebStorm 2018.1), the fetch function’s first parameter is typed as Request | string. But modern browser Fetch APIs do accept URL objects directly—this is just a lag in the type definition, not a limitation of the actual API.
Solutions to Skip Type Assertions
1. Convert the URL Object to a String (Simplest Fix)
The easiest way to avoid type errors is to call toString() on your URL object. This converts it to a properly formatted string URL that fits the existing type definition perfectly:
const url = new URL("https://api.example.com/data"); url.searchParams.append("filter", "active"); const fetchOptions: RequestInit = { method: "GET", headers: { "Accept": "application/json" } }; const response = await fetch(url.toString(), fetchOptions); const data = await response.json();
2. Update Your TypeScript/DOM Type Definitions
If you’re using a project-level TypeScript setup, upgrade to a newer TypeScript version (3.3 or later). Starting from TS 3.3, the RequestInfo type (the official type for fetch’s first parameter) includes URL objects. This lets you pass the URL directly without any workarounds:
const url = new URL("https://api.example.com/data"); url.searchParams.append("sort", "desc"); const response = await fetch(url, fetchOptions); // No type errors!
If you can’t upgrade TypeScript entirely, update the @types/web or @types/node packages (whichever provides your DOM type definitions) to a version that includes the updated RequestInfo definition.
3. Extend the Type Definition Manually
If upgrading isn’t an option, add a custom type extension file to your project to patch the RequestInfo type. Create a file named custom-dom.d.ts in your project root with this content:
declare global { type RequestInfo = string | Request | URL; } export {};
Make sure this file is included in your tsconfig.json’s include array so TypeScript picks it up. This will let the compiler recognize URL objects as valid inputs for fetch.
Is This a WebStorm Issue?
Not really. The problem comes from the outdated DOM type definitions bundled with that older WebStorm version. Newer versions of WebStorm (2020+) include updated TypeScript and DOM type definitions that natively support passing URL objects to fetch—so upgrading WebStorm would also resolve this long-term.
内容的提问来源于stack exchange,提问作者Marecky

