How to Build Multi Type Multidimensional Arrays in TypeScript ?
Last Updated :
02 Apr, 2024
TypeScript, multi-type multidimensional Arrays allow us to create arrays that can hold elements of multiple types at each level of the array hierarchy. we will learn how to build multi-type multidimensional arrays.
These are the following methods:
Using Union Types
In this method, we use union types to define an array type that can hold elements of different types.
Syntax:
let multiArray: (string | number)[][]
Example: In this example, we create a Multi Type Multidimensional Arrays using union Types
JavaScript
type MultiTypeArray = (number | string | boolean)[][][];
const multiArray: MultiTypeArray = [
[[1, 'two', true], [false, 'five', 6]],
[['seven', 8, true], [false, 10, 'eleven']]
];
console.log(multiArray);
Output
[
[
[ 1, 'two', true ],
[ false, 'five', 6 ]
],
[
[ 'seven', 8, true ],
[ false, 10, 'eleven' ]
]
]
Using Tuple Types
In this method Tuple types are used to specify arrays with fixed lengths and element types, making them suitable for multidimensional arrays
Syntax:
let multiTypeArray: [string, number][]
Example: In this example, we create a Multi Type Multidimensional Arrays Using Tuple Types
JavaScript
type MultiTypeTuple = [number | string | boolean][][][];
const multiTuple: MultiTypeTuple = [
[[1, 'two', true], [false, 'five', 6]],
[['seven', 8, true], [false, 10, 'eleven']]
];
console.log(multiTuple);
Output
[
[
[ 1, 'two', true ],
[ false, 'five', 6 ]
],
[
[ 'seven', 8, true ],
[ false, 10, 'eleven' ]
]
]
Using Interface Types
In this method we define custom interfaces representing multidimensional arrays, specifying the types of elements at each level.
Syntax:
interface Person { name: type1; age: type2; }
let multiTypeArray: Person[]
Example: In this example, we create a Multi Type Multidimensional Arrays Using Interface Types
JavaScript
interface MultiTypeArray {
[index: number]: (number | string | boolean)[][];
}
const multiInterface: MultiTypeArray = [
[[1, 'two', true], [false, 'five', 6]],
[['seven', 8, true], [false, 10, 'eleven']]
];
console.log(multiInterface);
Output
[
[
[ 1, 'two', true ],
[ false, 'five', 6 ]
],
[
[ 'seven', 8, true ],
[ false, 10, 'eleven' ]
]
]
Share your thoughts in the comments
Please Login to comment...