How to define an array of strings in TypeScript interface?

Typescript

Typescript Problem Overview


I have an object like this:

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

How to define address in an interface? the number of elements in the array is not fixed.

Typescript Solutions


Solution 1 - Typescript

interface Addressable {
  address: string[];
}

Solution 2 - Typescript

An array is a special type of data type which can store multiple values of different data types sequentially using a special syntax.

TypeScript supports arrays, similar to JavaScript. There are two ways to declare an array:

  1. Using square brackets. This method is similar to how you would declare arrays in JavaScript.
let fruits: string[] = ['Apple', 'Orange', 'Banana'];
  1. Using a generic array type, Array.
let fruits: Array<string> = ['Apple', 'Orange', 'Banana'];

Both methods produce the same output.

Of course, you can always initialize an array like shown below, but you will not get the advantage of TypeScript's type system.

let arr = [1, 3, 'Apple', 'Orange', 'Banana', true, false];

https://www.tutorialsteacher.com/typescript/typescript-array">Source</a>

Solution 3 - Typescript

It's simple as this:

address: string[]

Solution 4 - Typescript

Or:

{ address: Array<string> }

Solution 5 - Typescript

I think the best way to do it is something like: type yourtype = { [key: string]: string[] }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAngeloCView Question on Stackoverflow
Solution 1 - TypescriptderkoeView Answer on Stackoverflow
Solution 2 - TypescriptHusniddin QurbonboyevView Answer on Stackoverflow
Solution 3 - TypescriptMark DolbyrevView Answer on Stackoverflow
Solution 4 - TypescriptDaniel KhoroshkoView Answer on Stackoverflow
Solution 5 - TypescriptAxhio DevView Answer on Stackoverflow