cjones26
cjones26

Reputation: 3804

Is there a better way to define a "wrapped" JSON object without violating TS principles?

I recently began working with TypeScript and have come across an issue which I am curious if TypeScript provides any facilities for. I am reaching out to a web service which accepts data requests in the following format:

{
    "data": {
        "country": "US"
        "customerType": "Internal"
        "customer": "ABC"
    }
}

As you can see, the actual JSON request is "wrapped" with the "data" object, thereby requiring me to define my classes as such:

export class CalculatorRequest {
    data: CalculatorRequestData
}

export class CalculatorRequestData {
    country: string;
    customerType: string;
    customer: string;
}

Is there any way to avoid having to have the secondary, internal data class of type "CalculatorRequestData"?

I understand I can craft my request to avoid needing the internal class, but I would like to see if there are any more efficient options.

Thanks!

Upvotes: 0

Views: 44

Answers (1)

user47589
user47589

Reputation:

Using a generic will let you only make the 'data' objects, while you'll only ever need the one 'request' object.

export class ApiRequest<T> {
    data: T
}

export class CalculatorRequestData {
    country: string;
    customerType: string;
    customer: string;
}

// no extra request object needed, regardless of how many requests you have
export class FoooData {
    foo: string;
    bar: number;
}

Upvotes: 1

Related Questions