How to Define an Array of Strings in Typescript Interface?

How to Define an Array of Strings in Typescript Interface?

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.

1

5 Answers

interface Addressable {
  address: string[];
}
2

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];

Source

It's simple as this:

address: string[]

Or:

{ address: Array<string> }

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.