Code Logo

Typed Tuple [string, number]

Published at25 Jul 2026
TypeScript Collections Easy 0 views
Like0

Write a TypeScript function that takes a tuple [string, number] representing a person (name, age) and returns a formatted string like "Name (age)". Tuples in TypeScript are arrays with fixed lengths and typed elements at each position.

Tuple types allow specifying the type of each element at a specific position: [string, number] means element 0 must be a string and element 1 must be a number. This provides more precision than a plain array type string[] or (string | number)[]. Accessing tuple elements returns the correct type at each index.

TypeScript also supports optional tuple elements, rest elements in tuples, and labeled tuples for documentation. Tuples are commonly used for function return types (returning multiple values), CSV row representation, and coordinate pairs where each position has a specific meaning.

Time complexity is O(1) for accessing tuple elements by index. Space complexity is O(1). Tuple types are a compile-time concept that compiles to regular JavaScript arrays with no runtime overhead.

Edge cases include accessing out-of-bounds indices (caught by the compiler for fixed-length tuples), tuples with optional elements, and ensuring the return type matches the expected string format.

Example Input & Output

Example 1
Input
["Eve",35]
Output
Eve (35)
Explanation

Another format

Example 2
Input
["Diana",22]
Output
Diana (22)
Explanation

Younger person

Example 3
Input
["Bob",25]
Output
Bob (25)
Explanation

Another person

Example 4
Input
["Alice",30]
Output
Alice (30)
Explanation

Format name and age

Example 5
Input
["Charlie",40]
Output
Charlie (40)
Explanation

Another example

Algorithm Flow

Recommendation Algorithm Flow for Typed Tuple [string, number]
Recommendation Algorithm Flow for Typed Tuple [string, number]

Solution Approach

function solution(person: [string, number]): string {
  return person[0] + ' (' + person[1] + ')';
}

Best Answers

typescript - Approach 1
function solution(person: [string, number]): string {
  return person[0] + ' (' + person[1] + ')';
}