如何在typescript文件中推送一个字符串?

时间:2017-02-16 18:48:21

标签: angular typescript

我有一个名为

的班级
export class Channel {
  name: string
}

我有一个对象items: Channel[];

我有一个数组test[] = { "one", "two", three" }

如何将这些文本推送到项目对象。

1 个答案:

答案 0 :(得分:1)

据我所知,Channel类仅用于类型检查。

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