ThisParameterType?function greet(this: {name: string}, greeting: string) { return `${greeting}, ${this.name}!`; } const greetFn: (greeting: string) => string = greet; const obj = { name: "Alice", greet: greetFn }; console.log(greetFn("Hello"));
ThisParameterType extracts the type of this parameter, but the function is assigned without binding this.The function greet expects this to be an object with a name property. However, when assigned to greetFn, this is lost because the function is called without a proper this context, causing this to be undefined in strict mode, leading to a TypeError.
newFn after applying OmitThisParameter to fn in this code?function fn(this: {x: number}, y: number): number { return this.x + y; } type FnNoThis = OmitThisParameter<typeof fn>; const newFn: FnNoThis = (y) => fn.call({x: 10}, y); console.log(newFn(5));
OmitThisParameter removes the this parameter from the function type, so newFn only takes y.OmitThisParameter creates a function type without the this parameter. The new function newFn calls fn with a bound this object {x: 10}. So calling newFn(5) returns 10 + 5 = 15.
this parameter to a variable without it. Why does TypeScript show an error here?function show(this: {name: string}) { console.log(this.name); } const fn: () => void = show;
this parameters affect assignability.Functions with explicit this parameters are not assignable to functions without them because the this parameter is part of the function's type signature in TypeScript.
ThisParameterType do?ThisParameterType extracts.ThisParameterType extracts the type of the this parameter from a function type, if it exists. If the function has no this parameter, it returns unknown.
ThisParameterType and OmitThisParameter?function multiply(this: {factor: number}, value: number): number { return this.factor * value; } type FactorType = ThisParameterType<typeof multiply>; const obj: FactorType = { factor: 3 }; type MultiplyNoThis = OmitThisParameter<typeof multiply>; const multiplyNoThis: MultiplyNoThis = (value) => multiply.call(obj, value); console.log(multiplyNoThis(5));
obj is typed using ThisParameterType and how multiplyNoThis calls multiply with obj as this.ThisParameterType extracts the type of this from multiply, which is { factor: number }. The object obj matches this type. OmitThisParameter creates a function type without this. The function multiplyNoThis calls multiply with obj as this, so multiplyNoThis(5) returns 3 * 5 = 15.