Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define an array of strings in TypeScript interface?

Tags:

typescript

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.

like image 325
AngeloC Avatar asked Aug 20 '17 08:08

AngeloC


People also ask

How do you declare an array of objects in TypeScript interface?

To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!

How do you define an interface array?

To define an interface for an array of objects, define the interface for the type of each object and set the type of the array to be Type[] , e.g. const arr: Employee[] = [] . All of the objects you add to the array have to conform to the type, otherwise the type checker errors out.

Can you define an array of strings?

We can have an array with strings as its elements. Thus, we can define a String Array as an array holding a fixed number of strings or string values. String array is one structure that is most commonly used in Java. If you remember, even the argument of the 'main' function in Java is a String Array.

Should I use [] or array in TypeScript?

There is no difference at all. Type[] is the shorthand syntax for an array of Type . Array<Type> is the generic syntax. They are completely equivalent.


1 Answers

interface Addressable {   address: string[]; } 
like image 66
derkoe Avatar answered Sep 28 '22 01:09

derkoe