【发布时间】:2021-12-15 00:48:31
【问题描述】:
这是一个衍生问题
Object Property method and have the good inference of the function in TypeScript
谢天谢地,@jcalz 的代码有效;
const P = <T,>(x: T) => ({ "foo": <U,>(R: (x: T) => U) => R(x) });
现在我编写了一个高级代码,以避免每次函数调用都创建新对象。
想法是首先用_P(undefined)创建一个基础对象,然后通过Object.defineProperty改变属性值来重用该对象。
它几乎可以工作,但如下所示,会产生类型错误:2345:
'(a: number) => number' 类型的参数不能分配给'(x: undefined) => number' 类型的参数。 参数“a”和“x”的类型不兼容。 类型“未定义”不可分配给类型“数字”。(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
有解决此错误的想法吗?谢谢!
【问题讨论】:
标签: typescript