TypeScript无法自动推导Promise返回类型的问题咨询
Promise<string[]> for Your filesAsync Function Great question! Let’s break down why TypeScript is inferring Promise<{}> instead of the expected Promise<string[]> and how to fix it without explicitly specifying the generic type on the Promise constructor.
Why You’re Seeing Promise<{}>
TypeScript infers the type of a Promise based on the argument passed to its resolve callback. If TypeScript can’t clearly determine the type of value resolve will receive—for example, if the resolve parameter isn’t typed, or if there’s ambiguous code flow—it defaults to the broadest possible type, often {} (an empty object type) or unknown in newer TypeScript versions.
Fix 1: Type the resolve Callback Parameter
The simplest way to guide TypeScript’s inference is to add a type annotation directly to the resolve parameter in the Promise constructor. This tells TypeScript exactly what type of value the Promise will resolve to, and it will automatically infer the correct Promise<string[]> return type for your function:
const files: string[] = ["document.pdf", "image.png"]; function filesAsync() { // Add type annotation to resolve return new Promise((resolve: (value: string[]) => void) => { // Simulate async operation setTimeout(() => { resolve(files); }, 1000); }); } // Now TypeScript correctly infers filesAsync returns Promise<string[]> const result = filesAsync(); // result: Promise<string[]>
Fix 2: Ensure Resolved Value Type is Unambiguous
If your async logic has conditional branches or intermediate variables, make sure every path that calls resolve passes a value of type string[]. Avoid accidentally widening the type to any or unknown during processing:
function filesAsync() { return new Promise((resolve) => { // Process files but preserve the string[] type const processedFiles = files.map(file => `processed-${file}`); // still string[] resolve(processedFiles); }); }
Here, since processedFiles is clearly a string[], TypeScript will infer the Promise resolves to string[] without extra annotations.
Why Explicit Generic Works (and Why You Might Prefer Inference)
When you write new Promise<string[]>(...), you’re directly telling TypeScript the Promise’s resolved type. The fixes above achieve the same result by letting TypeScript infer the type from the code itself, which can make your code more maintainable—if the resolved type ever changes, you won’t have to update the generic parameter manually.
内容的提问来源于stack exchange,提问作者Picci

