【问题标题】:How to define a data type in typescript for arrays?如何在 typescript 中为数组定义数据类型?
【发布时间】:2017-10-20 22:39:47
【问题描述】:

我正在尝试将数组类型定义为基本上如下所示:

[
  {
    name: string,
    comment: string
  },
  {
    name: string,
    comment: string
  }
]

但无论数组中有多少个 cmets,它都需要工作。

我发现了一些像 How to define array type in typescript? 这样的人设置长度的例子

但我无法让它为我正在做的事情工作,这里是上下文:

class Post{
  person: string;
  bird: string;
  content: string;
  image: string;
  comments: Array<MyType>;
  score: number;
  grade: number;
  constructor(p: string, b: string, c: string, i: string = '', cm: Array<MyType> = []) {
    this.person = p
    this.bird = b
    this.content = c
    this.image = i
    this.comments = cm
    this.score = 0
    this.grade = this.score + this.cm.length
  }
}

我应该如何定义类型 MyType?

【问题讨论】:

    标签: arrays class typescript types constructor


    【解决方案1】:
    class Post{
      person: string;
      bird: string;
      content: string;
      image: string;
      comments: Array<{name:string, comment:string}>;
      score: number;
      grade: number;
      constructor(p: string, b: string, c: string, i: string = '', cm: Array<{name:string, comment:string}> = []) {
        this.person = p
        this.bird = b
        this.content = c
        this.image = i
        this.comments = cm
        this.score = 0
        this.grade = this.score + this.cm.length
      }
    }
    

    【讨论】:

    • 好的,所以你只定义数组中的类型而不是数组的整个结构?
    • 是的,这就是您在 javascript 中模拟类型安全检查的方式,您只需告诉它您的列表包含的对象的“形状”
    【解决方案2】:

    我总是更喜欢interface ovre class

    interface Post{
      person: string;
      bird: string;
      content: string;
      image: string;
      comments: Array<Comment>;
      score: number;
      grade: number;
    }
    interface Comment{
        name : string;
        comment:string;
    }
    

    【讨论】:

    • 我不会将Post 转换为接口,因为来自OP 的Post 类的构造函数中有一些逻辑。 Comment 作为接口应该没问题。
    • 如果您使用模型(自定义数据类型),您可以使用界面。在实例保持不变的情况下,编写类和创建实例有时会很麻烦。
    • OP 中的构造函数及其内部逻辑意味着Post 不仅提供结构(应首选接口),而且还创建Post 的实际实例你不能使用接口。
    • 我只是想要一种有组织的方式来为我正在制作的 Angular 4 应用程序创建示例数据,但它仍然无法正确编译,所以我决定先制作 api
    猜你喜欢
    • 2019-05-30
    • 2019-01-23
    • 2020-12-11
    • 2021-06-14
    • 2020-07-24
    • 2021-03-15
    • 2020-05-18
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多