How to define a `typescript array of strings` in an interface?

How to define a typescript array of strings in an interface?

I have an object like this:

{
  "address": ["line1", "line2", "line3"]
}

How can I define the address property in an interface when the number of elements in the array is not fixed?

Hi

It’s the most common question that I think even I faced issue when I started my coding jounery. Heres what I follow:

Using a simple array type: You can define the address property as a generic array of strings in the interface like this:

interface MyObject {
  address: string[];
}

This allows the address property to hold an array of any number of strings.

If you want to specify that the array should hold strings but the number of elements is not fixed, you can use a tuple type that allows for an indefinite number of strings:

interface MyObject {
  address: string[]; // This works just like an array, with no specific length constraint
}

If you want to enforce some range for the number of elements in the array, you could use something like the following. However, this is less flexible:

interface MyObject {
  address: [string, ...string[]];  // The first element is required, and the rest can be strings.
}

Each solution ensures the address is a typescript array of strings and can accommodate varying lengths.