How to work with JSON containing numerical variable names in TypeScript

Looking at the JSON data from Swagger, I noticed that there are response codes represented as numbers in the "responses" section. For example, the responses include 200, 404, and 503 along with their descriptions.

"responses": {
  "200": {
    "description": "OK"
  },
  "404": {
    "description": "not found"
  },
  "503": {
    "description": "Problem with external dependency"
  }
}

I'm wondering about the best approach to deserialize this JSON into a Typescript object. Should I create a service to process this data before passing it on to Typescript, or is there a simpler solution? My initial thought is to handle it in javascript first and then transform it into a more easily consumable format for Typescript. Before I start coding, I want to explore if there's a more efficient way to tackle this task.

Answer №1

TypeScript is a language that exists only during the compilation process; at runtime, it is all converted into plain JavaScript.

When (de)serialization occurs at runtime, the data is deserialized into a JavaScript object. However, if you are asking if it's possible to create a TypeScript type definition for this incoming object, then the answer is yes.

It's important to note that the property names in TypeScript are not numbers but strings that may contain numeric values. This differentiation matters when creating type definitions because a string and a number are considered different types.

The first step is to define the Response objects:

interface IResponse {
  description: string;
}

There are two approaches for defining the Responses object. The first approach can be used when the property names are known beforehand, while the second approach is more generic and supports any property names of a given type.

Known Names

interface IKnownResponses {
  "200": IResponse;
  "300"?: IResponse;
  "400": IResponse;
}

This interface requires properties named "200" and "400", with the option to have a property named "300".

The "300" property is optional as indicated by the ? symbol in its definition.

Dynamic Names

interface IDynamicResponses {
    [responseCode: string]: IResponse;
}

This interface allows any string to be used as a key/property name, with each property containing an IResponse.

It is essentially an indexer definition.

Example

You can see these approaches in action with the following code snippet:

interface IResponse {
  description: string;
}

interface IKnownResponses {
  "200": IResponse;
  "300"?: IResponse;
  "400": IResponse;
}

interface IDynamicResponses {
    [responseCode: string]: IResponse;
}

let knownResponses: IKnownResponses = {
    "200": {
    description: "foo"
  },
  "400": {
    description: "bar"
  }
};

let dynamicResponses: IDynamicResponses = {
    "200": {
    description: "foo"
  },
  "400": {
    description: "bar"
  },
  "401": {
    description: "baz"
  }
};

console.log(staticResponses["200"].description);
console.log(knownResponses["401"].description);

https://jsfiddle.net/L8dpomL8/3/

While JSFiddle might not provide the best TypeScript IDE environment, you can copy this code to your preferred IDE to experiment and explore how typings can assist or fall short in your specific scenario.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps do I need to take to develop a personalized validation directive (an attribute used for validation) in Angular 2.0?

I have embarked on a small project involving Angular 2.0 and TypeScript. From what I understand, Angular 2.0 does not come equipped with built-in validators for the "min" and "max" attributes. I am aware of the process to create a custom validator and asso ...

What is the process for bringing a graphql file into typescript?

I'm having trouble importing a graphql file and encountering an error import typeDefs from "./schema/schema.graphql"; 10 import typeDefs from "./schema/schema.graphql"; ~~~~~~~~~~~~~~~~~~~~~~~~~ at cre ...

Struggling to extract a value from a non-JSON string. Any tips on how to retrieve the desired data from this particular string format?

Example Here is a sample string a:1:{i:0;a:4:{s:8:"priority";i:0;s:6:"amount";s:2:"20";s:4:"type";s:5:"above";s:5:"total";s:1:"0";}}. How can one extract the value of s:2 from this non-JSON string? ...

Issue encountered when attempting to login via VK in the app, rather than the webView Dialog

Hello there, I am currently facing a problem with a social network application that has already been released. Users are unable to log in through the VK application due to a JSON error that VK is claiming to be the SDK fingerprint error. I have done extens ...

Combine functions from two objects that share the same properties into an array for each property

I need help combining the methods from two objects into one, resulting in an array of methods for each property in the parent object: obj1 = {"prop1":"method1","prop2":"method2"} obj2 = {"prop1":"method3","prop2":"method4"} Expected result: obj1 = {"pro ...

Oops! Property 'month' cannot be set on undefined value due to a TypeError

Despite not receiving any errors from Visual Studio Code, I’m encountering an error in Chrome's console. Below is the code snippet from my interfaces.ts file: export interface Data1{ month: string; employeeName: string; date: string; employmentSta ...

Is it possible to inject a descendant component's ancestor of the same type using

When working with Angular's dependency injection, it is possible to inject any ancestor component. For example: @Component({ ... }) export class MyComponent { constructor(_parent: AppComponent) {} } However, in my particular scenario, I am tryin ...

Creating GeoJson using JavaScript

Currently, I am retrieving a latitude/longitude array using Ajax $.ajax({ type: "POST", url: '../m/m_share.php', data: 'zone=' + zone, dataType: 'json', success: function(tab) { var i = 0; ...

Encountering an issue of receiving an undefined response while attempting to retrieve JSON data from a

I'm trying to access JSON data from this specific URL: here However, I keep receiving an undefined value when attempting to retrieve it. Strangely, I can view the JSON data in the response using developer tools, but for some reason, I am unable to p ...

Removing numerous elements in JSON structures

name_list = [{'name': 'John'}, {'name': 'Johan'}, {'name': 'John'}] for i in xrange(len(name_list)): if name_list[i]["name"] == "John": del name_list[i] Once the code rec ...

What is the interpretation of this error message and is there a solution I can apply to resolve

Utilizing the tweepy API, I am streaming specific information and saving it into a CSV. While tweets are being stored successfully, an error message keeps appearing: ('failed ondata', 'coercing to Unicode: need string or buffer, NoneType fou ...

I am looking to replicate a DOM element using Angular 4

I am interested in creating a clone of a DOM element. For example, if I have the following structure: <div> <p></p> <p></p> <p></p> <p></p> <button (click)="copy()"></button> & ...

Tips for Implementing CdvPurchase.Store in Angular

Is there a way to configure cordova-plugin-purchase v13 in conjunction with Angular 15? Here is a snippet of what I have attempted. Below is my PaymentService class that is set to be provided at the root level. // payment.service.ts import { Injectable } ...

Developing an NPM package within a yarn workspace monorepo featuring internal dependencies

Currently, I am working on a project where I am utilizing yarn workspace to develop a library that will eventually be published on NPM. This library has a dependency on a private core package within the same workspace. As per my understanding, the workspac ...

I'm curious about the Next.js type that corresponds to the Redirect object

It's possible to set up redirection in Next.js by configuring it like this: module.exports = { async redirects() { return [ { source: '/about', destination: '/', permanent: true, }, ] ...

Retrieving the initial element from a JSON data

Having trouble accessing all data elements from the "api_data" in this JSON response. I attempted various methods to retrieve the "api_data" but I am only able to retrieve the first element. It is puzzling why the rest of the data is not appearing in the ...

Creating asynchronous JavaScript constructors using a static method called "create" presents challenges when dealing with TypeScript types

I've been diving into the world of asynchronous constructors and have successfully implemented them in JavaScript. However, I'm facing a challenge with TypeScript types. Here's how it should ideally work: const a: AnyClass = await AnyClass. ...

Access the assets by calling the getAssets() method from a different class. This allows you to view the loadJSON

Welcome to the community! I am facing an issue with using getAssets() from a class other than the main one. It works fine in my MainActivity Class, but when I try to use getAssets() in my other Class through LoadJSONFromAsset(), it doesn't work. I hav ...

How to effectively test @input using Jasmine: Anticipated Object did not match undefined

Having trouble with this error. There seems to be something missing but can't pinpoint what it is. The task at hand is simple: just test this basic component. Let's take a look: import { Component, OnInit, Input } from '@angular ...

Ways to ensure that a FILE type object is able to be serialized as

When attempting to send a JSON response in Django, I encountered the following error: TypeError: Object of type File is not JSON serializable This error was caused by utilizing type <class 'django.core.files.base.File'> in my JSON respon ...