At this time, TypeScript does not have a native way to achieve this functionality (without resorting to something like a type assertion, which is not recommended).
Currently, the arguments
object is assigned the IArguments
type, which resembles an array with its numeric index signature and a numeric length
property. However, it lacks enough typing information to determine the argument types at specific indexes or the exact literal type of the length
property:
function f(a: number, b: number) {
const arg0 = arguments[0];
// const arg0: any
const len = arguments.length;
// const len: number
}
In essence, while IArguments
is similar to an array, it lacks the specificity of being tuple-like. There has been ongoing discussion on enhancing the typing of arguments
in the issue tracker at microsoft/TypeScript#29055. It's possible that a specialized IArguments<T>
type could be introduced in the future, functioning like a stripped-down tuple type without array-specific methods. This poses some challenges due to the current spread behavior only applicable to actual tuples as function arguments. So, creating a custom IArguments<T>
may not seamlessly integrate with existing syntax, such as calling
f(...arguments)</code while preventing invalid operations like <code>arguments.map(x => x)
.
As of now, this feature is not integrated into the language. To work around this limitation, one would need to rely on type assertions or similar techniques.
Access the code example here