Paracetamol.ts?? #47 Explica este código TypeScript

TypeScript avanzado con tipos literales y mapped types: ConteoAnimal a partir de Animal, por qué falta conejo genera error y cómo hacer propiedades opcionales o usar Partial.

18 sept 2025 • 2 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Problema planteado y respuesta correcta B: Property conejo is missing in type { perro: number; gato: number; } but required in type ConteoAnimal

Descripción del código en TypeScript y explicación avanzada: tenemos un tipo literal llamado Animal que agrupa los valores perro, gato y conejo. A partir de ese tipo se crea un mapped type llamado ConteoAnimal usando la sintaxis [U in Animal]: number. Esa construcción obliga a que ConteoAnimal tenga una propiedad para cada literal definido en Animal, y que el valor de cada propiedad sea de tipo number. Al declarar el objeto miAnimal con solo las propiedades perro y gato y sin incluir conejo, el compilador de TypeScript marca un error de tipo en tiempo de compilación porque falta la propiedad conejo que ConteoAnimal requiere. Por eso la opción correcta es B.

Cómo solucionarlo: 1) Añadir la propiedad conejo al objeto miAnimal, por ejemplo asignándole un número. 2) Si queremos que no todas las claves sean obligatorias, modificar el mapped type para que las propiedades sean opcionales usando [U in Animal]?: number o bien usar Partial al declarar miAnimal. 3) Otra alternativa es cambiar la definición de Animal para reflejar solo los literales que realmente necesitamos.

Conceptos clave implicados: mapped types, tipos literales union, comprobación estructural de tipos en TypeScript y seguridad de tipos en tiempo de compilación. Los mapped types son muy útiles cuando queremos relacionar dos tipos y garantizar que un objeto tenga exactamente las claves derivadas de un conjunto de literales, lo que ayuda a evitar errores en ejecución al forzar la presencia o forma de las propiedades en fase de compilado.

En Q2BSTUDIO somos especialistas en desarrollo de software y aplicaciones a medida, y aplicamos buenas prácticas de tipado como las de TypeScript para construir soluciones robustas. Si necesitas aplicaciones a medida y software a medida podemos ayudarte a diseñar arquitecturas escalables y seguras. Además ofrecemos servicios de inteligencia artificial y consultoría para integrar modelos y agentes IA en tus procesos; conoce más sobre nuestros servicios de inteligencia artificial para empresas.

Palabras clave relacionadas: aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA, power bi. También trabajamos con soluciones de business intelligence y herramientas como Power BI para convertir datos en decisiones, además de ofrecer ciberseguridad y pentesting para proteger tus aplicaciones y servicios cloud.

Resumen práctico: la opción B es la respuesta correcta porque TypeScript exige que ConteoAnimal incluya las propiedades correspondientes a todos los literales de Animal; al omitir conejo el objeto miAnimal no cumple la forma requerida y el compilador falla.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat