1

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?

2 Answers 2

4
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
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

okay so you only define the types of what will be in the aray not the whole structure of the array?
Yes, that's how you emulate type safety checking in javascript, you just need to tell it the "shape" of the objects your list contains
0

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

4 Comments

I wouldn't convert Post as an interface as the constructor for Post class from the OP has some logic in it. Comment should be fine as an interface though.
if you are using models(custom datatype) you can go with the interface. Writing class and creating a instance will trouble some time when instance remains unchanged.
The constructor an the logic inside it from the OP implies that Post is not only just to provide structure (where interfaces should be preferred), but also to create an actual instance of Post which you can't with interfaces.
i just wanted an organized way to create sample data for an angular 4 app i am making, its still not compiling correctly so i decided to just make the api first

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.