Using TypeScript to create aliases for JSON properties

Imagine I need to fetch data from Visual Studio TFS and the response (in json format) looks like this:

{
    "Microsoft.VSTS.Scheduling.StoryPoints": 3.0,
    // ......
}

The property names have dots. After researching, I learned in TypeScript I can create an interface like this:

export interface IStory { // This interface might not be very helpful
    "Microsoft.VSTS.Scheduling.StoryPoints": number
}

To access the property, I could use the following syntax:

var story = GetStoryFromTFS();
console.log(story["Microsoft.VSTS.Scheduling.StoryPoints"]);

However, I'd rather not access the property this way because it won't provide suggestions through intellisense due to using a string key.

In C#, there is a JsonProperty attribute to define a model like this:

public class Story
{
    [JsonProperty(PropertyName = "Microsoft.VSTS.Scheduling.StoryPoints")]
    public double StoryPoints { get; set; }
}

This allows me to access the property as follows:

var story = GetStoryFromTFS();
Console.WriteLine(story.StoryPoints);

With this approach, intellisense can assist in selecting the desired property.

Is there an equivalent of JsonProperty attribute in TypeScript? Or perhaps a better method to achieve this functionality in TypeScript?

Answer №1

There are several ways to handle this situation. It's important to remember that in each case, you'll need to pass the original data to the accessing class.

One approach is mapping the values:

class StoryMap {
    constructor(data: IStory) {
        this.StoryPoints = data["Microsoft.VSTS.Scheduling.StoryPoints"];
     }

    StoryPoints: number;
}

Another option is wrapping the data:

class StoryWrap {
    constructor(private data: IStory) {}

    get StoryPoints(): number { return this.data["Microsoft.VSTS.Scheduling.StoryPoints"] };
}

You could also create a decorator to map the data:

function JsonProperty(name: string) {
    return function DoJsonProperty(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        descriptor.get = function () {
            return this.data[name];
        }
        descriptor.set = function (value) {
            this.data[name] = value;
        }
    }
}

class StoryDecorator
{
    constructor(private data: IStory) {}

    @JsonProperty("Microsoft.VSTS.Scheduling.StoryPoints")
    get StoryPoints(): number { return 0 };

}

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

Encountering a lack of response when making an ajax call to CouchDB

Being relatively new to CouchDB, I appreciate your patience. Currently, I have set up an instance of CouchDB on a VM. It can be accessed without any issues through the browser via futon or directly at: http://192.168.62.128:5984/articles/hot_dog Althoug ...

The callback functions designed to ascertain non-conflicting time ranges are harmoniously aligned

Suppose I have a JSON dataset of events, each with start and end times, and I want to create a function that generates time ranges without conflicts. For example, if the dataset includes 0800-0845, 1200-1230, 1140-1240, 1430-1530, etc., how can I gray ou ...

Please provide the JSON format for including tags in a status update on IBM Connections

I am attempting to programmatically post a status update to the activity stream within IBM Connections 4.0. I am currently trying to figure out where to place this JSON code: "tags":[{"objectType":"tag","displayName":"ibms"}], So far, I have tried the fo ...

Having trouble with Node.js express.json middleware parsing request differently than anticipated

For my express server, I am using a simple cURL command to post a small JSON object: curl -d "{'test': 'this'}" localhost:3000/rest/user/authenticate In my Express setup, I have configured body parsing to handle JSON posts: // enabli ...

Accessing embedded JSON data in Javascript: A step-by-step guide

{ "category": [ { "category_id": "1", "category_name": "Top Picks ", "cover_url": "http://www.example.com" }, { "category_id": "2", "category_name": "Latest Releases", "cover_url": "http://www.exa ...

Decoding JSON data for integration into highchart.js

When extracting multiple values from a database, performing calculations in a servlet, and returning the results to the front end for visualization using highchart.js, I currently create a JSON string that is consumed by highcharts. However, I am consideri ...

What could be causing me to have difficulty retrieving JSON data with PHP?

Below is the content of the JSON file: // [ { "id": "5417778" ,"t" : "TATAMTRDVR" ,"e" : "NSE" ,"l" : "329.80" ,"l_fix" : "329.80" ,"l_cur" : "Rs.329.80" ,"s": "0" ,"ltt":"11:11AM GMT+5:30" ,"lt" : "Jul 26, 11:11AM GMT+5:30" ,"lt_dts" : "2016-07-2 ...

extract and process nested dictionaries stored within a JSON array

Is there a way to transform the following JSON structure: json_decode = [{"538":["1,2,3","hello world"]},{"361":["0,9,8","x,x,y"]}] into this format: {"538":["1,2,3","hello world"],"361":["0,9,8","x,x,y"]} using Python? ...

Acknowledgment Pop-up

When using the PrimeNG table with a custom modal component that I created, I encountered an issue. The edit functionality works correctly and retrieves the correct row id, however, the delete function always returns the id of the first row. dashboard.html ...

What causes TypeScript to generate an error when using two array of object types, but not when using the shape of both?

There are two basic types of data available: type DataA = { percent: string; exchange: string; }; type DataB = { price: number; exchange: string; }; I'm puzzled as to why TypeScript gives errors when I try to use both types together: const ...

Tips for programmatically focusing on a v-textarea using Vuetify and TypeScript

It feels impossible right now, I've attempted some unconventional methods like: (this.refs.vtextarea as any).textarea.focus() ((this.refs.vtextarea as Vue).$el as HTMLElement).focus() and so on... Javascript source code is quite complex for me to ...

How to compare two arrays of JSON objects and display specific data using PHP

I'm looking at an array of JSON objects below. This data is stored in the file (feeds/ptp-ess_landing_house.json), referenced at Line A. { "house_sitting_date_current_month": ["2020-02-01", "2020-02-02", "2020-02-03", "2020-02-04", "2020-02-05", ...

Using JavaScript to retrieve a JSON file stored locally

Having trouble with my code and a statistics.json file - it keeps saying data is not defined when I try to log it. Any suggestions for solving this issue? const showStatistics = function(){ fetch("../assets/statistics.json") .then(res =& ...

Converting numerical values from string to float in JSON format

I am facing an issue with converting a Json (received as text) in my Swift code. Here is how I convert it: if let jsonData = raw.data(using: String.Encoding.utf8) { if let json = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) ...

Issues with parsing Json data

Here is a JSON file: { "noticiaDTOs": [ { "idiomaPais": { "idioma": { "id": 3, "iso6391": "pt" }, "pais": { "id&quo ...

The presence of a method is triggering an Error TS2741 message stating that the property is missing in type

Here is a simplified code snippet that highlights the issue I am facing: class Test { prop1 : boolean prop2 : string method() { } static create(prop1 : boolean, prop2 : string) : Test { let item : Test = { prop1: prop1, prop2: pro ...

classes_1.Individual is not a callable

I am facing some difficulties with imports and exports in my self-made TypeScript project. Within the "classes" folder, I have individual files for each class that export them. To simplify usage in code, I created an "index.ts" file that imports all class ...

"Unsubscribing in Angular via a button click: A step-by

I'm having trouble canceling a subscription for "device orientation" in Angular using (click) in HTML. I've tried multiple solutions but none seem to work. Does anyone have any ideas on how to fix this? TS // Watching the change in device compa ...

Is there a way to extract data from a JSON string literal in Python without making any changes to it?

This specific data fits the criteria of a valid json string: {"key": "quoted \"value\" and 'value'"} However, due to the presence of both ' and " in the value, these examples are considered inva ...

Using React to sort and retrieve only the duplicate values in an array

Within this Array, I am retrieving all the idCategory values of "answersTo", some of which are duplicates. I'm trying to filter out only those duplicates, but it's not a straightforward comparison since there is no specific data to compare agains ...