Home > Software engineering >  How to define an array of objects
How to define an array of objects

Time:01-11

Using vue 3, typescript and eslint

I have the following code:

...
data() {
  return {
    blah: '',
    blah2: []
    ...

and in the methods object I have:

methods: {
  addEntry() :void {
    this.blah2.push({s:'whatever',b:false});
  }
  ...

I'm getting this error:

Argument of type '{ s: string; b: boolean; }' is not assignable to parameter of type 'never'

I've tried the following, none of which work:

blah2: any[] = []

blah2: Array<{ s: string, b: Boolean }> = Array()

blah2: Array<{ s: string, b: Boolean }>[] = []

blah2: { s: string, b: Boolean } = []

blah2: { s: string, b: Boolean }[] = []

blah2: any[{ s: string, b: Boolean }] = []

What is the correct way to do this?

Note: If I hardcode some initial data like so:

...
data() {
  return {
    blah: '',
    blah2: [
      {s:'whatever',b:false}
    ]
    ...

then it has no problem, so, I guess, it is working the declaration out from the data.

CodePudding user response:

You need to set the return type of the function
See example here

  • Related