Type receiver arguments
Type the receiver supplied to Function.prototype.apply or call when a function declares an explicit this parameter.
TypeScript · Type Alias
ThisParameterType<Type> extracts a function's explicit this-parameter type. It returns unknown when the function type has no this parameter.
ThisParameterType<Type> inspects a function type and extracts the type declared for its special this parameter. If the function declares no this parameter, the result is unknown; the utility is for extracting an existing contextual this type, not transforming another type.
ThisParameterType<Type>| Name | Type | Description |
|---|---|---|
Type | function type | A function type whose explicit this parameter should be extracted. |
The type declared by the function's this parameter, or unknown when the function type has no this parameter.
function toHex(this: Number) {
return this.toString(16);
}
function numberToString(n: ThisParameterType<typeof toHex>) {
return toHex.apply(n);
}
console.log(numberToString(255));The extracted this type is used to type the value passed to apply.
Type the receiver supplied to Function.prototype.apply or call when a function declares an explicit this parameter.
Derive a reusable receiver type from an existing function declaration without duplicating its annotation.
Build generic function helpers that inspect receiver requirements from a function type.
It extracts the type of a function's special this parameter. If that parameter is absent, the result is unknown.
Follow-up: What happens for an arrow function? Its lexical this is not declared as a function this parameter, so this utility does not recover a receiver type from it.
The type argument is normally a function type, often obtained with typeof from a function declaration. The resulting type can then annotate a receiver value passed through APIs such as apply.
Follow-up: How would you preserve both the receiver and ordinary arguments? Combine ThisParameterType with Parameters<Type> and an appropriate call signature.
It was released in TypeScript 3.3. It differs from ThisType<T>, which is a marker used for contextual this typing in object literals rather than an extractor.
Follow-up: Why can ThisType<T> not replace it? ThisType<T> supplies contextual information; ThisParameterType reads a declared this parameter from a function type.
ThisType<T>Parameters<Type>OmitThisParameter<Type>