TypeScript - implementing Mapped Types and Conditional Types for Complex Object Transformations
Hey everyone, I'm running into an issue that's driving me crazy. I'm currently working on a TypeScript project where I need to transform a complex object structure into a different format using mapped types and conditional types. However, I'm running into issues with type inference that leads to unexpected behavior and type errors. My goal is to transform an object where each property is an array of objects into an object where each property is an array of transformed objects. Here's the initial structure I'm working with: ```typescript interface InputObject { users: { id: number; name: string }[]; products: { id: number; title: string }[]; } const input: InputObject = { users: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }], products: [{ id: 1, title: 'Laptop' }, { id: 2, title: 'Phone' }], }; ``` I want to create a mapped type that transforms this into: ```typescript interface OutputObject { users: string[]; // Only names products: string[]; // Only titles } ``` I attempted to implement this transformation using the following mapped type: ```typescript type Transform<T> = { [K in keyof T]: T[K] extends Array<infer U> ? U extends { title: string } ? U['title'][] : U extends { name: string } ? U['name'][] : never : never; }; const output: Transform<InputObject> = { users: input.users.map(user => user.name), products: input.products.map(product => product.title), }; ``` Despite my efforts, I'm running into the following TypeScript behavior: ``` Type 'string[]' is not assignable to type 'never[]'. ``` I've double-checked the logic in my mapped type but need to seem to figure out why it outputs `never` instead of the expected string arrays. I also tried breaking down the logic into simpler parts but the behavior continues. Can anyone provide insights into what might be going wrong or suggest a more effective way to achieve the desired transformation?