CodeBlanks Logo Icon CodeBlanks

Tuple inference

Learn tuple inference in generics.

What is tuple inference?

Tuple inference is the inference of the tuple type from the arguments passed in a generic function call. In function f<T extends unknown[]>(...args: T): T, T is determined as the tuple of the ordered types of the parameters in the call. This provides type-safe tuple return with rest parameters.

function f<T extends unknown[]>(...args: T): T {
  return args;
}
f(1, "a", true);  // [number, string, boolean]

Tuple return with rest parameters

When a function returns rest parameters as a tuple, the return type preserves the type order of the call arguments. Unlike a normal array return, this keeps the element types and order fixed. So the call f(1, "a") returns [number, string].

Practice Tuple returning function

Define a generic function named dondur: <T extends unknown[]>(...args: T): T. Its body should be return args. Assign the result of calling dondur(1, "a", true) to a variable named sonuc. Print sonuc[0] with console.log.

Starter code

index.ts
// dondur adinda generic fonksiyon tanimla
// rest parametre ile T tuple olarak cikarilsin
// fonksiyon kendisini geri döndürsün
// cagriyi sonuc'a ata
// sonuc[0] yazdir

Sample solution

index.ts
function dondur<T extends unknown[]>(...args: T): T {
  return args;
}
const sonuc = dondur(1, "a", true);
console.log(sonuc[0]);

Expected output

1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In the call f(1, "a") to function f<T extends unknown[]>(...args: T): T, what is T?

  • unknown[]
  • [number, string] Correct answer
  • (number | string)[]
  • any[]

Explanation: With rest parameters, the ordered types of the call arguments are inferred as a tuple; so T becomes [number, string], not a union array.

2 Rest parameter declaration

Question
function f<T extends unknown[]>(____ args: T): T {
  return args;
}
Answer
function f<T extends unknown[]>(... args: T): T {
  return args;
}

Explanation: Rest parameters are declared with the ... prefix; this collects a variable number of arguments into a single array.

3 Tuple inference concepts

Term Meaning
...args Rest parameter
T extends unknown[] Tuple constraint
[number, string] Inferred tuple type
inference Type inference

All lessons in Advanced