Kevin Olomu
Kevin Olomu

Reputation: 782

TypeScript create a class with properties that are known in runtime

I get the following response from a REST-Service:

[{
  "id": "1",
  "name": "Jon Doe"
  "paymentInformation": {
    "cc": {
      "type": "visa",
      "number": "123456789"
    },
    "btc": {
      "address": "123asdsa12d4as6d54sad23"
    },
    "bank-wire": {
      "bank-name": "Best Bank",
      "IBAN": "123456789987654321",
      "BIC": "47114711123",
      "Owner": "Jon Doe"
    }
  }
},{...}
]

Every Object is a customer.

My main problem is to create a class which is should represent the paymentInformation. I will know the keys at runtime (when I get the json response).

How can I create such a class in TypeScript?

That's what I currently have:

export class Customer {
  constructor(
    public id: number, 
    public name: string, 
    public paymentInformation: PaymentInformation)   { }
}

Upvotes: 0

Views: 40

Answers (1)

Fenton
Fenton

Reputation: 250932

If the data you have shown is the correct shape of the data, but where the actual keys are likely to differ, what you have is:

  • An indexer, that returns... another indexer that returns strings.

On in TypeScript:

interface PaymentInformation {
    [key: string]: { [key: string]: string };
}

This is quite a wide type, it will only check that:

  • Level 1 keys are strings
  • Level 1 values are indexers... that match:
  • Level 2 keys are strings
  • Level 2 values are strings

For example:

const paymentInfo: PaymentInformation = {
    "str": {
        "str2": "value",
        "other": "val"
    },
    "another": {
        "so on": "etc"
    }
};

Upvotes: 1

Related Questions