2017-08-15 52 views
1

我需要將以下代碼轉換爲TypeScript。它是一個包含對象的數組。然後我想在課堂中使用它。我試圖使用一個界面,但我無法進行太多的工作。請幫幫我。JS代碼轉換爲Typescript

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

您的幫助非常感謝。

+1

只是要清楚,您無需對此進行任何更改即可成爲有效的打字稿 – cYrixmorten

+0

您在問什麼是TypeScript方式? –

回答

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

非常感謝。我們如何用類對象調用它? – Ubunto

+0

您的發送代碼中存在一些錯誤 我在http://www.typescriptlang.org/play上運行 – Ubunto

+1

它工作[在此jsFiddle](https://jsfiddle.net/j7mbq6ky/1/) – Kokodoko