TypeScript如何为函数定义与参数结构一致但值为布尔的返回类型?
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 inputqueryis 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 inputTmaps to a boolean value—exactly the structure you want the function to return.- The type assertions (
as keyof Tandas { [K in keyof T]: boolean }) help TypeScript bridge the gap between the dynamic nature ofObject.keys()(which returnsstring[]) 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

