JS代码转换为Typescript

时间:2017-08-15 14:32:20

标签: javascript typescript

我需要将以下代码转换为TypeScript。它是一个包含对象的数组。然后我想在课堂上使用它。我试图使用一个界面,但我无法进行太多。请帮帮我。

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

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

如果要对帐户模型数据进行类型检查,可以使用类型别名

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

现在,您的IDE将检查您的变量是否包含正确的内容:

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
 };