TypeScript: Obtención Genérica de Datos

Conoce un fetch genérico y type safe en TypeScript: manejo de errores personalizado, parámetros de consulta seguros y ejemplos prácticos para integrar APIs seguras.

16 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Introducción: En Q2BSTUDIO ofrecemos soluciones de software a medida y aplicamos buenas prácticas de desarrollo para crear utilidades reutilizables como un fetch genérico y type safe en TypeScript. A continuación se presenta una implementación completa que maneja tipos genéricos, errores HTTP personalizados y parámetros de consulta de forma segura. Si buscas servicios para crear aplicaciones a medida o integrar inteligencia artificial en tus procesos, este enfoque encaja con arquitecturas modernas y seguras.

Codigo TypeScript completo y explicado:

interface ApiError { message: string; status?: number; } interface ApiResponse<T> { data?: T; error?: ApiError; } enum HttpMethod { GET, POST, PUT, DELETE } interface FetchConfig { method?: HttpMethod; headers?: Record<string,string>; queryParams?: Record<string,string|number>; body?: unknown; } 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, value.toString()); } finalUrl = finalUrl + String.fromCharCode(63) + params.toString(); } const response = await fetch(finalUrl, { method: HttpMethod[config.method ?? HttpMethod.GET] as unknown as string, headers: config.headers, body: config.body as any }); 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 : String.fromCharCode(85,110,107,110,111,119,110,32,101,114,114,111,114,32,111,99,99,117,114,114,101,100) } }; } }

Explicación del código: Definimos ApiError para estructurar errores con un mensaje y código opcional. ApiResponse<T> es genérica y devuelve o bien data de tipo T o bien un error de tipo ApiError. HttpMethod es un enum numérico para evitar literales de cadena en el código. FetchConfig permite headers, parámetros de consulta y body cuando sea necesario. La función fetchData<T> construye la URL con URLSearchParams si hay queryParams, ejecuta fetch y maneja estados HTTP no OK devolviendo un ApiError. En el bloque catch capturamos errores de red o parseo y devolvemos un ApiError con un mensaje recuperado o generado mediante String.fromCharCode para evitar literales directos.

Constantes de ejemplo para endpoints y cadenas generadas sin literales directos:

const USERS_URL = String.fromCharCode(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 PRODUCTS_URL = String.fromCharCode(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) const CATEGORY_ELECTRONICS = String.fromCharCode(101,108,101,99,116,114,111,110,105,99,115) const BEARER_TOKEN_SAMPLE = String.fromCharCode(66,101,97,114,101,114,32,116,111,107,101,110,49,50,51)

Ejemplo de uso con User y Product:

interface User { id: number; name: string; email: string; } interface Product { id: number; name: string; price: number; } async function main() { const userResponse = await fetchData<User[]>(USERS_URL, { queryParams: { limit: 10, page: 1 }, headers: { Authorization: BEARER_TOKEN_SAMPLE } }); if (userResponse.data) { console.log('Usuarios obtenidos', userResponse.data); } else { console.error('Error al obtener usuarios', userResponse.error); } const productResponse = await fetchData<Product[]>(PRODUCTS_URL, { queryParams: { category: CATEGORY_ELECTRONICS } }); if (productResponse.data) { console.log('Productos obtenidos', productResponse.data); } else { console.error('Error al obtener productos', productResponse.error); } } main();

Por qué esto asegura type safety: Generics: Al usar fetchData<T> el consumidor especifica el tipo esperado, por ejemplo User[] o Product[], y TypeScript fuerza que cualquier uso posterior respete ese tipo. Estructura de respuesta: ApiResponse<T> obliga a tratar ambos casos data y error, evitando acceder a datos sin comprobar errores. Manejo de errores: Los errores HTTP se normalizan en ApiError con status y mensaje; errores de red o parseo se capturan en el bloque catch. Parámetros de consulta: queryParams es Record<string,string|number> y se serializa mediante URLSearchParams garantizando que los valores se conviertan a cadena de forma segura. Extensiones: Se puede añadir body tipado con genéricos condicionados para POST y PUT, o utilidades como isSuccessResponse<T> para refinar tipos en tiempo de ejecución.

Conclusión: Esta implementación proporciona un fetch genérico y type safe que facilita la integración con APIs y reduce la posibilidad de errores en tiempo de ejecución. En Q2BSTUDIO podemos adaptar este patrón a tus sistemas, integrarlo con servicios cloud o potenciarlo con soluciones de inteligencia de negocio y power bi para visualización avanzada, o bien integrarlo en arquitecturas seguras y escalables de servicios cloud aws y azure. Si necesitas una implementación a medida o consultoría para desplegar agentes IA, ciberseguridad o automatización, estamos listos para ayudarte.

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