What is the array.toString() method in TypeScript?

Overview

The toString() method of an array in TypeScript is used to return the string representation of all the elements of the array.

Syntax

array.toString()
Syntax of the toString() method in TypeScript

Parameter

array: This is the array we want to get the string representation of.

Return value

This method returns a string containing the combined elements of the array.

Example

// create arrays in TypeScript
let names: string[] = ["Theodore", "James", "Peter", "Amaka"]
let numbers : Array<number>;
numbers = [12, 34, 5, 0.9]
let cars : Array<string> = ["Porsche", "Toyota", "Lexus"]
let randomValues : Array<string | number> = ["one",1, "two", 2, 56]
// get the arrays as strings
let str1 = names.toString()
let str2 = numbers.toString()
let str3 = cars.toString()
let str4 = randomValues.toString()
// print the arrays as strings
console.log("String representation:",str1, "| Data type:",typeof(str1))
console.log("String representation:",str2, "| Data type:",typeof(str2))
console.log("String representation:",str3, "| Data type:",typeof(str3))
console.log("String representation:",str4, "| Data type:",typeof(str4))

Explanation

  • Lines 2–6: We declare four arrays and initialize them with elements.
  • Lines 9–12: We get the string representations of the arrays using the toString() method.
  • Lines 15–18: We print the string representation of the arrays and the data type of the returned string on the console.

Free Resources