Gonçalo
Gonçalo

Reputation: 156

Using a JSON Dictionary with Typescript

I have two json dicionary files, each with the same terms from two different languages.

{
   "Account" : {
      "AccountLockText" : "Your account is locked",
      "Login" : {
         "CreateAccount" : "Create an account",
         "LoginBtn" : "Login",
         "LoginHeader" : "Login"
      }
   }
}

And I have a dictionaries.d.ts:

declare module "dictionaries" {
    var Account: any;
}

To be called and used with typescript in my application. Sad part is that said file is empty, and I have no idea how to make that kind of connection.

Can someone help me with this?

Upvotes: 0

Views: 2850

Answers (1)

Fenton
Fenton

Reputation: 250892

I usually use a simple interface to describe a JSON message I'm getting back from a service call:

interface AccountData {
    Account: {
        AccountLockText: string;
        Login: {
            CreateAccount: string;
            LoginBtn: string;
            LoginHeader: string;
        }
    }
}

Here's an example of it in action (I'm just parsing a JSON string to show you how it adds the type information from the interface I use in the type annotation).

const data = `{
"Account" : {
    "AccountLockText" : "Your account is locked",
    "Login" : {
        "CreateAccount" : "Create an account",
        "LoginBtn" : "Login",
        "LoginHeader" : "Login"
    }
}
}`;

let result: AccountData = JSON.parse(data);

alert(result.Account.Login.CreateAccount);

Upvotes: 2

Related Questions