Home > OS >  How to implement such an object?
How to implement such an object?

Time:09-11

I need to implement an object of type on ts:

{
    "validElements": {
        "classNames": [],
        ...: []
    }, 
    "invalidElements": {
        "classNames": [],
        ...: []
    }
}

My code and error:

interface outputObject {
    "validElements": {
        "classNames": Array
    }, 
    "invalidElements": {
        "classNames": Array
    }
}

The universal type "Array" requires the following number of type arguments: 1.

But the bigger question here is how do I then use such an interface to add and remove values from it. In fact, I have an eventlistener where I validate the fields and, depending on the value, add a class to one or another array, and then return the object

Also, I will need to add values and delete from arrays that are inside the object. I tried to do it through the interface, but I get the error that arguments are required. How to do it more correctly?

CodePudding user response:

create an object and specific your type to that object and also change your type from Array to Array<string> as per the first answer.

const outputObject: OutputObject = {
 "validElements": {
        "classNames": []
 }, 
 "invalidElements": {
        "classNames": []
 }
}

CodePudding user response:

Array is generic type which requires type arguments. You can do it like this:

interface OutputObject {
  validElements: {
    classNames: string[];  
  }
  invalidElements: {
    classNames: string[];  
  }
}

Note that string[] is shortcut for Array<string>.

  • Related