2017-02-16 23 views
-5

我有一個類叫做如何推送打字稿文件中的字符串?

export class Channel { 
    name: string 
} 

我有一個對象items: Channel[];

我有一個數組test[] = { "one", "two", three" }

如何推動這些文本項對象。

+1

我有以下的語法很難。如果你想推入一個數組,你的items數組需要被初始化。你能分享一個更好的代碼表示嗎?並使用SO提供的代碼樣式? – kenhowardpdx

+1

'測試'不是一個適當的對象。即使將其放在方括號內,它仍然無效。 –

回答

1

通道類只用於類型檢查,據我所知。

Channel.ts

export class Channel { 
    name: string; 
} 

Items.ts

import { Channel } from './Channel'; 

const items: Channel[] = []; // initialize to empty array 
const test: string[] = ["one", "two", "three"]; 

// because 'test' is an array of strings we need to convert each item 
// to be a Channel 

const channels = test.map(t => { return { name: t } as Channel }); // the 'as Channel' part is only for type checking 

// assign 'channels' to 'test' 
test.push(...channels); 

這裏有一個工作示例:http://codepen.io/kenhowardpdx/pen/dNLeoJ?editors=0012

+0

明白了。謝謝。 – test