【问题标题】:How to push a string in typescript file? [closed]如何在打字稿文件中推送字符串? [关闭]
【发布时间】:2017-07-06 01:18:39
【问题描述】:

我有一门课叫

export class Channel {
  name: string
}

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

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

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

【问题讨论】:

  • 我很难理解你的语法。如果你想推入一个数组,你的 items 数组需要被初始化。你能分享一个更好的代码表示吗?并使用 SO 提供的代码样式?
  • test 不是一个合适的对象。即使你把它放在方括号内,它仍然是无效的。

标签: angular typescript


【解决方案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

【讨论】:

  • 知道了。谢谢。
猜你喜欢
  • 2020-12-22
  • 2019-06-26
  • 2017-08-21
  • 2021-06-18
  • 2020-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-24
相关资源
最近更新 更多