WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

TypeScript · Basic · question 13 of 100

How can you define an array in TypeScript?

📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

In TypeScript, you can define an array in multiple ways. Here are the three most common methods to define an array:

1. Using square bracket ‘[]‘ notation:

let arr1: number[] = [1, 2, 3, 4, 5];
let arr2: string[] = ['one', 'two', 'three', 'four', 'five'];

2. Using generic ‘Array‘ type notation:

let arr3: Array<number> = [1, 2, 3, 4, 5];
let arr4: Array<string> = ['one', 'two', 'three', 'four', 'five'];

3. Using an angle-bracket type assertion:

let arr5 = <number[]>[1, 2, 3, 4, 5];
let arr6 = <Array<string>>['one', 'two', 'three', 'four', 'five'];

All of these methods create and define an array with specified types. It’s usually recommended to use the first or the second way because they are more explicit and, in the case of the first one, more concise.

Here is a comparison table of these array definition methods:

Notation Type Syntax Example
Square Bracket dataType[] let arr: number[] = [1, 2, 3];
Generic Array Array<dataType> let arr: Array<number> = [1, 2, 3];
Angle-Bracket Type Assertion <dataType[]> let arr = <number[]>[1, 2, 3];

When working with multidimensional arrays, you can define them as follows:

// Two-dimensional array of numbers
let matrix: number[][] = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

In this example, the type ‘number[][]‘ denotes a two-dimensional array of numbers. You can do the same with other data types and other dimensions.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic TypeScript interview — then scores it.
📞 Practice TypeScript — free 15 min
📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

All 100 TypeScript questions · All topics