CodexBloom - Programming Q&A Platform

TypeScript: How to Properly Type a Generic Function with Predicate Argument and Return Type?

πŸ‘€ Views: 61 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-22
typescript generics type-safety

This might be a silly question, but I'm trying to create a generic filter function in TypeScript that takes an array and a predicate function. The scenario arises when I attempt to type the return value correctly. I want the function to return a filtered array of the same type as the input array, but I'm running into a typing scenario with the predicate function. Here’s the code I have so far: ```typescript function filterArray<T>(arr: T[], predicate: (item: T) => boolean): T[] { return arr.filter(predicate); } const numbers: number[] = [1, 2, 3, 4, 5]; const filteredNumbers = filterArray(numbers, (num) => num > 3); console.log(filteredNumbers); // Output: [4, 5] const strings: string[] = ['apple', 'banana', 'cherry']; const filteredStrings = filterArray(strings, (str) => str.startsWith('b')); console.log(filteredStrings); // Output: ['banana'] ``` So far, this works as expected for both numbers and strings. However, when I try to pass an object array with a property filter like this: ```typescript type User = { id: number; name: string; } const users: User[] = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, ]; const filteredUsers = filterArray(users, (user) => user.name.includes('a')); console.log(filteredUsers); ``` I get the following behavior: ``` Argument of type '(user: User) => boolean' is not assignable to parameter of type '(item: T) => boolean'. ``` The typing seems to break down with the object array. I suspect it has to do with how TypeScript infers the types from the function, but I'm not exactly sure how to resolve it. Any insights on how I can ensure my generic function retains type safety across various data structures would be greatly appreciated! The stack includes Typescript and several other technologies.