1

I need to convert the following code into TypeScript. It is an array with objects. and then I want to use it inside a class. I tried to use an interface but I could not proceed much. Please help me.

var accountModel = {
        name: 'ABC Account',
        accounts: [
            { balance: 10000, description: 'Checking' },
            { balance: 50000, description: 'Savings' }
        ]
    };

Your help is very much appreciated.

2
  • 1
    Just to be clear, you do not need to make any changes for this to be valid typescript Commented Aug 15, 2017 at 14:35
  • Are you asking what's the TypeScript way ?
    – OB Kenobi
    Commented Aug 15, 2017 at 14:36

1 Answer 1

4

If you want type checking on your account model data, you can use type aliases

type AccountModel = {name:string, accounts:Array<Account>}
type Account = {balance:number, description:string}

Now your IDE will check if your variable has the correct content:

let acc : AccountModel = {
        name: 'ABC Account',
        accounts: [
            { balance: 10000, description: 'Checking' },
            { balance: 50000, description: 'Savings' }
        ],
        test: 'hello' // The IDE will complain: 'test' is
                      // not assignable to accountModel
 };
5
  • Thanks a lot. How we can call it with a class object?
    – azizsagi
    Commented Aug 15, 2017 at 14:56
  • there are some errors in your sent code I run on typescriptlang.org/play
    – azizsagi
    Commented Aug 15, 2017 at 15:00
  • 1
    I even created a version with classes and interfaces in this jsfiddle :) I think this is better!
    – Kokodoko
    Commented Aug 15, 2017 at 20:06
  • thank you. how I can convert the following directive into TS. App.directive('emp', [function ($scope) { return function (scope,element,attrs) { if (scope.name === "ABC") element.css({color:'red'}); }; }]);
    – azizsagi
    Commented Aug 16, 2017 at 7:27
  • I think that's a different question :) But it should already work in typescript, even if you don't define the types explicitly. Also, defining the types for nested anonymous functions can become a bit unreadable, I'd prefer rewriting the code in a more OOP way to avoid this.
    – Kokodoko
    Commented Aug 16, 2017 at 10:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.