Home > Software engineering >  How to predefine object with element as an array <string> type?
How to predefine object with element as an array <string> type?

Time:03-15

I have an object, and i need to define in this object sub element, which will be as an array. But how do i define it's type? Without type definition it throws error.

Implicitly has any[]

let someObject = {
  somePropety: {
    A : 0,
    B : 0,
    C : []<string>,
  }
}

Does anyone know how to asign C element an array of string type ?

CodePudding user response:

You seem to be looking for

let someObject = {
  someProperty: {
    A: 0,
    B: 0,
    C: [] as string[],
  },
};

Alternatively, you can declare the type of the entire someObject variable (see @wooooooo's or @ksav's answers for that) instead of using a type assertion on the empty array literal.

CodePudding user response:

You're looking for string[]. However, it doesn't look like your example is a type definition?

I would write it like this:

let someObject: { somePropety: { A: number; B: number; C: string[] } } = {
        somePropety: {
          A: 0,
          B: 0,
          C: []
        }
}; 

CodePudding user response:

C: string[]

you have to do it like this

CodePudding user response:

If you are trying to define C as an array of strings, you can do:

C: string[];

or using a generic array type:

C: Array<string>

You can find more detail on TypeScript basic types here

CodePudding user response:

Create an interface for your object, so that you can explicitly type it.

interface MyObject {
    somePropety: {
        A: number
        B: number
        C: string[]
    }
}

let someObject: MyObject = {
  somePropety: {
    A : 0,
    B : 0,
    C : ['a', 'b', 'c'],
  }
}
  • Related