Tengo un problema al escribir la función genérica y reduje mi problema a esto:
Al combinar el tipo A genérico con cualquier objeto B regular, TypeScript ignora por completo el genérico y lo trata como B .
interface RegularObjType { regularKey: string; } interface BaseObjType { baseKey: string; } function addBasePropertyToObject<T extends { [key: string]: any }>( genericObj?: T, regularObj?: RegularObjType ) { const baseObject: BaseObjType | undefined = { baseKey: "baseValue" }; const baseWithRegular = { ...baseObject, ...regularObj }; const baseWithGeneric = { ...baseObject, ...genericObj }; return { baseWithRegular, baseWithGeneric }; } const {baseWithGeneric, baseWithRegular} = addBasePropertyToObject( { genericKey: "genericValue" }, { regularKey: "regularValue" } );Tipos asumidos por TypeScript:
// baseWithRegular type is combination of both const baseWithRandom: { randomKey?: string | undefined; baseKey: string; } // baseWithGeneric type is just baseObject const baseWithGeneric: { baseKey: string; }Debido a eso, no tengo acceso a las claves genéricas que pasé a la función.
// 👇 Works const {baseKey: baseKey1, regularKey} = baseWithRegular // 👇 Property 'genericKey' does not exist on type '{ baseKey: string; }'. const {baseKey: baseKey2, genericKey} = baseWithGeneric¿Hay alguna manera de mejorar la escritura en este caso particular?
Enlace del espacio aislado de código: https://codesandbox.io/s/gracious-stallman-bbr2ek?file=/src/index.ts