132

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
    I strongly suggest reading the documentation. Commented Aug 20, 2017 at 9:23

7 Answers 7

242
interface Addressable {
  address: string[];
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thumbs up for a well-named interface.
As an extension, if you have a custom interface lets say Customer and you need to have another parent interface which should have List then it would be like Customer[]
@AluanHaddad can you explain more why the interface name is good?
@Ooker because it is an adjective. It describes a capability or behavior as opposed to a lineage.
31

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

Comments

11

It's simple as this:

address: string[]

Comments

11

This is the answer I came here for:

enum Lines {
  "line1",
  "line2",
  "line3",
}

interface Addressable {
   address: keyof typeof Lines;
}

Comments

4

Or:

{ address: Array<string> }

Comments

3

I think the best way to do it is something like:

type yourtype = { [key: string]: string[] }

1 Comment

This would define a type of an object with property keys as strings, each of which would hold a value of a string array, which is not what OP asked.
0

Here is how the cool kids do it nowadays.

export type stringArray = [string][number][];

Explanation:

[string] creates a tuple of string

[number] cast the tuple into a string

[] declares it as an array

For non believers, here is the proof:

enter image description here

2 Comments

What is better about this than just using String[] ? (Aside from it not being as cool)
it has nothing better than string[] other than being less readable. but at least you learn about type casting in Typescript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.