2016-11-05 64 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)