This question is related to
Object Property method and having good inference of the function in TypeScript
Fortunately, the code provided by @jcalz is working fine;
const P = <T,>(x: T) => ({ "foo": <U,>(R: (x: T) => U) => R(x) });
I have now written an advanced code that avoids creating a new object on every function call.
The approach is to first create a base object with _P(undefined)
and then reuse the object by changing the property value using Object.defineProperty
.
It almost works, but there is a type error 2345 being produced:
Argument of type '(a: number) => number' is not assignable to parameter of type '(x: undefined) => number'. Types of parameters 'a' and 'x' are incompatible. Type 'undefined' is not assignable to type 'number'.(2345)
const f: (a: number) => number
const _P = <T,>(x: T) =>
({ "foo": <U,>(R: (x: T) => U) => R(x) });
const P =
(obj =>
<T,>(x: T) =>
Object.defineProperty(obj, "foo", {
configurable: true, //property value changes
value: <U,>(R: (x: T) => U) => R(x)
})
)(_P(undefined));
const f = (a: number) => a + 1;
const b = P(99)['foo'](f); //const b: number //good
//however, `f` is marked as type error 2345
console.log(b);//100
https://i.sstatic.net/AYaaG.png
Any suggestions on how to resolve this error? Thank you!