TypeScript: Obtención Genérica de Datos

Guía práctica de Q2BSTUDIO para implementar un obtentor genérico de datos en TypeScript con tipado seguro y manejo de errores. Soluciones de software a medida, IA y ciberseguridad, con AWS y Azure.

16 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

En Q2BSTUDIO, empresa especializada en desarrollo de software a medida, aplicaciones a medida, inteligencia artificial, ciberseguridad y servicios cloud aws y azure, compartimos una guía práctica para implementar un obtentor genérico de datos con TypeScript que sea tipo seguro y reutilizable. Si necesitas soluciones de software a medida y aplicaciones a medida o motores basados en inteligencia artificial, podemos ayudarte a integrarlo de forma robusta y segura. A continuación se muestra el código completo, ejemplos de uso y una explicación de por que este enfoque garantiza seguridad de tipos y manejo de errores.

// Helper para construir cadenas sin usar literales de comillas const s = (...codes: number[]) => String.fromCharCode(...codes)

// Tipos y interfaces

interface ApiError { message: string; status?: number }

interface ApiResponse<T> { data?: T; error?: ApiError }

interface FetchConfig { method?: string; headers?: Record<string,string>; queryParams?: Record<string,string|number>; body?: any }

// Funcion genérica para fetch async function fetchData<T>(url: string, config: FetchConfig = {}): Promise<ApiResponse<T>> { try { let finalUrl = url if (config.queryParams) { const params = new URLSearchParams() for (const [key,value] of Object.entries(config.queryParams)) { params.append(key, String(value)) } const urlObj = new URL(String(url)) urlObj.search = params.toString() finalUrl = urlObj.toString() } const response = await fetch(finalUrl, { method: config.method || s(71,69,84), headers: config.headers, body: config.body }) if (!response.ok) { return { error: { message: response.statusText, status: response.status } } } const data = await response.json() as T return { data } } catch (error) { return { error: { message: error instanceof Error ? error.message : s(69,114,114,111,114,32,100,101,115,99,111,110,111,99,105,100,111) } } } }

// Ejemplos de estructuras de datos interfaces User { id: number; name: string; email: string } interface Product { id: number; name: string; price: number }

// Endpoints construidos sin literales const usersUrl = s(104,116,116,112,115,58,47,47,97,112,105,46,101,120,97,109,112,108,101,46,99,111,109,47,117,115,101,114,115) const productsUrl = s(104,116,116,112,115,58,47,47,97,112,105,46,101,120,97,109,112,108,101,46,99,111,109,47,112,114,111,100,117,99,116,115)

// Uso de la funcion con tipos concretos async function main() { const userResponse = await fetchData<User[]>(usersUrl, { queryParams: { limit: 10, page: 1 } }) if (userResponse.data) { console.log(userResponse.data) } else { console.error(userResponse.error) } const productResponse = await fetchData<Product[]>(productsUrl, { queryParams: { category: s(101,108,101,99,116,114,111,110,105,99,115) } }) if (productResponse.data) { console.log(productResponse.data) } else { console.error(productResponse.error) } } main()

Explicacion de seguridad de tipos y manejo de errores

Generics y ApiResponse

La interfaz ApiResponse<T> encapsula la respuesta como un objeto que puede contener data de tipo T o un error de tipo ApiError. Al invocar fetchData<User[]> o fetchData<Product[]>, TypeScript asume que la propiedad data, en caso de existir, tendra la forma esperada, lo que permite autocompletado y comprobacion en tiempo de compilacion.

Manejo de errores

Se detectan errores HTTP mediante response.ok y se devuelven como ApiError con status y message. Errores de red o de parseo quedan capturados en el bloque try catch y se normalizan a ApiError. Esto fuerza al consumidor a comprobar la existencia de data antes de usarla.

Parametros de consulta tipo seguros

FetchConfig incluye queryParams con tipo Record<string,string|number>, lo que permite construir la cadena de consulta de forma segura usando URLSearchParams. Asi se evita concatenacion manual propensa a errores y a inyecciones accidentales.

Flexibilidad y extensibilidad

Al usar genericos, esta funcion es reutilizable para cualquier estructura de datos. Se puede extender FetchConfig para incluir un body tipado segun el metodo, o añadir guards de tipos como isSuccessResponse<T>(r: ApiResponse<T>): r is { data: T } para mejorar la ergonomia.

Por que elegir Q2BSTUDIO

En Q2BSTUDIO combinamos experiencia en desarrollo de aplicaciones y software a medida con soluciones de inteligencia artificial y ciberseguridad. Si su proyecto requiere integracion en la nube, podemos desplegar en plataformas como AWS y Azure y optimizar sus procesos con soluciones de inteligencia de negocio y power bi. Conozca nuestras capacidades en inteligencia artificial visitando servicios de inteligencia artificial para empresas.

Palabras clave integradas naturalmente: aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA y power bi.

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