w3resource

Calculating length of strings in TypeScript

TypeScript Advance Types: Exercise-8 with Solution

Write a TypeScript function that accepts a parameter of type string | string[] and returns the length of the input string. It also returns the sum of the lengths of all strings in the array. Use type assertions to let TypeScript know the parameter type.

Sample Solution:

TypeScript Code:

// Function 'calculateLength' that accepts a parameter of type 'string | string[]'
function calculateLength(input: string | string[]): number {
 // Use a type assertion to ensure 'input' is treated as an array of strings
 const strings: string[] = (typeof input === "string" ? [input] : input) as string[];
 // Calculate the total length of all strings in the array
 const totalLength = strings.reduce((length, str) => length + str.length, 0);
 return totalLength;
}
// Test the 'calculateLength' function
const singleString = "Hello, TypeScript!";
const stringArray = ["Coding", "TypeScript", "Exercise"];
const length1 = calculateLength(singleString); // Calculate length of a single string
const length2 = calculateLength(stringArray); // Calculate sum of lengths in an array
console.log("Length 1: "+ length1); // Output: 18 (length of the single string)
console.log("Length 2: "+ length2); // Output: 24 (sum of lengths of strings in the array)

Explanations:

In the exercise above -

  • First, we define a function "calculateLength()" that accepts an argument 'input' of type string | string[].
  • Use a type assertion to ensure that 'input' is treated as an array of strings. If 'input' is a string, we wrap it in an array [input], and if it's already an array of strings, we cast it using (input as string[]).
  • Calculate the total length of all strings in the array using the "reduce()" method and the str.length property.
  • The function returns 'totalLength', which is of type 'number'.
  • Finally, we test the "calculateLength()" function with a single string and an array of strings to demonstrate how it handles both cases.

Output:

"Length 1: 18"
"Length 2: 24"

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


Previous: Type assertion in TypeScript.
Next: TypeScript generic function example.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.