1

This seems like a dumb question, but here I am.

I know an interface can be used to define an object and its keys, but how do I make an interface if that object is an array?

For example, the interface for

const object = {
   bar: 1
   foo: 2
}

would be

interface myInterface {
   bar: number
   foo: number
}

What if my object is:

const object = [[1,2,3],[4,5,6],[7,8,0]]

What about a 3D array?

How do I define this interface?

1
  • it depends how precise you want to be, but first let me say that in for example vscode, just hovering over 'object' will tell you it's a number[][], a 3d array would be like number[][][]. As mentioned you can use tuples to be more restrictive about the length of the array, and account for different types in different positions Commented Oct 20, 2020 at 23:06

2 Answers 2

4

You could use tuples:

const object: [
  [number, number, number],
  [number, number, number],
  [number, number, number]
] = [[1,2,3],[4,5,6],[7,8,0]];

Or using a type additionally:

type Point3D = [
  [number, number, number],
  [number, number, number],
  [number, number, number]
];

const object: Point3D = [[1,2,3],[4,5,6],[7,8,0]];

Note: Point3D is restricted to exactly three times [number, number, number].

Sign up to request clarification or add additional context in comments.

1 Comment

This is what I was looking for, thanks. I figured the answer was going to be very very simple.
2

You can define a type for that, for example:

type MyArray = number[][];

To hold a 2D array of numbers.

Or you can use the tuple type if you want your arrays to have a set length or hold values of different types in different positions:

type MyArray = [number, number, number][];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.