You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript如何为函数定义与参数结构一致但值为布尔的返回类型?

Fixing TypeScript Type Error for getQueries Function

Great question! The root issue here is that TypeScript can’t automatically infer the specific keys of your input object when using Object.keys() and reduce() like this—it defaults to typing the return value as an empty object {}, which is why you get that "Property does not exist" error when accessing queries.first.

To fix this, we need to use generics and mapped types to tell TypeScript to preserve the exact structure of your input object, but with all values converted to booleans. Here’s how to update your function:

Solution 1: Modified Reduce Approach

function getQueries<T extends Record<string, string>>(query: T): { [K in keyof T]: boolean } {
  return Object.keys(query).reduce((list, key) => {
    // Assert key is a known key of T to avoid type mismatches
    const typedKey = key as keyof T;
    return { ...list, [typedKey]: query[typedKey].length > 3 };
  }, {} as { [K in keyof T]: boolean }); // Assert initial value matches our target return type
}

Let’s break down the key parts:

  • T extends Record<string, string>: This generic constraint ensures the input query is an object with string keys and string values (matching the structure you’re passing in).
  • { [K in keyof T]: boolean }: This mapped type creates a new type where every key from the input T maps to a boolean value—exactly the structure you want the function to return.
  • The type assertions (as keyof T and as { [K in keyof T]: boolean }) help TypeScript bridge the gap between the dynamic nature of Object.keys() (which returns string[]) and the specific keys of your input object.

Solution 2: Cleaner Object.fromEntries Approach

If you prefer a more concise implementation, you can use Object.entries() and Object.fromEntries() instead of reduce()—this often makes the logic easier to read:

function getQueries<T extends Record<string, string>>(query: T): { [K in keyof T]: boolean } {
  return Object.fromEntries(
    Object.entries(query).map(([key, value]) => [key, value.length > 3])
  ) as { [K in keyof T]: boolean };
}

Testing the Fixed Function

Now when you call the function, TypeScript will correctly infer the return type, and you won’t get errors when accessing properties:

const queries = getQueries({ first: 'dsds', second: 'dsdsds', third: 'ds' });

queries.first; // Type: boolean (no error!)
queries.second; // Type: boolean
queries.third; // Type: boolean

This approach ensures the return object’s structure is 100% aligned with your input, while keeping all values typed as booleans—exactly what you needed.

内容的提问来源于stack exchange,提问作者Alejandro Garcia Anglada

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 08:02:51