Bird Dad
Bird Dad

Reputation: 427

How to define a data type in typescript for arrays?

I am trying to define an array type to basically look like this:

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

but it needs to work no matter how many comments there are in the array.

I found some examples with set lengths like this guy How to define array type in typescript?

But I can't get it to work for what I am doing, here is the context:

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
  }
}

how should I define the type MyType?

Upvotes: 1

Views: 3354

Answers (2)

Trash Can
Trash Can

Reputation: 6814

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
  }
}

Upvotes: 4

Aravind
Aravind

Reputation: 41533

I always prefer 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;
}

Upvotes: 0

Related Questions