2016-11-05 57 views
-1

在打字稿類和第三方庫我見過...,我想知道如何使用它。什麼是在打字稿編程?

下面是一個來自ng2-admin模板的例子。我認爲它用於從該類中導入整個json。

export const PAGES_MENU = [ 
    { 
    path: 'pages', 
    children: [ 
     { 
     path: 'dashboard', 
     data: { 
      menu: { 
      title: 'Dashboard', 
      icon: 'ion-android-home', 
      selected: false, 
      order: 0 
      } 
     } 
     }, 
     { 
     path: 'editors', 
     data: { 
      menu: { 
      title: 'Editors', 
      icon: 'ion-edit', 
      order: 100, 
      } 
     } 
     } 
    ] 
} 
]; 


//use 
import { PAGES_MENU } from './pages/pages.menu'; 

export const MENU = [ 
    ...PAGES_MENU 
]; 

我想在這裏它導入整個JSON並導出它們在不同的類中使用。

回答

1

在您的示例中,它被稱爲spread operator,但...也可能是rest operator

function foo(x, ...y:number[]) { } // This is the rest operator, see below 
var args = [0, 1, 2]; 

// Instead of doing this 
foo("hello", args[0], args[1], args[2]) 

//You can do this 
foo("hello", ...args); // This calls foo like foo("hello", 0, 1, 2) 

// The function call gets compiled to this javascript: 
foo.apply(void 0, ["hello"].concat(args)); 

在打字稿這主要是與其他運營商一起使用,否則,你將有某種類型的錯誤:

function foo(x, y, z) { } 
var args = [0, 1, 2]; 

// Type error here 
foo(...args) 

// But you could get around it by: 
(foo as any)(...args) 

其餘的運營商允許您定義可以採取任何數量的參數的函數。而當你有這些時,如果你已經有了一個數組中的參數,那麼spread操作符是很方便的。

在你例子中的使用被編譯到正規片:

exports.MENU = PAGES_MENU.slice(); 
+0

所以它的一個JavaScript運營商不打字稿特殊。 –

+0

@AniruddhaDas它在ES2015中定義,並且TypeScript也處理它。 – Alex

1

這是spread syntax它在這裏用於(淺)複製數組。

在你的情況下,下面的表達式給出了相同的結果:

[...PAGES_MENU] 

PAGES_MENU.slice() 

Array.from(PAGES_MENU) 

PAGES_MENU.map(x => x)