TypeScript:在对象扩展方法中推断 <this> 的类型

TypeScript: Infer type of <this> in Object extension method

我正在尝试在 TypeScript 中实现与 kotlin 的 let scope function 类似的东西。

我目前的方法是使用声明与 Object 接口合并。这通常有效,但我缺少内部方法参数的类型信息(参见下面的示例)。

有没有办法推断调用函数的对象的类型?

interface Object {
  let: <S>(block: <T = this>(thisVal: T) => S) => S | null
}

Object.prototype.let = function <T, S>(block: (thisVal: T) => S): S | null {
  return this != null ? block(this as T) : null
}

const a = {foo: 42}
// don't want to write this -> 'a.let<typeof a>(it => console.log(it.foo));'
a.let(it => console.log(it.foo)); // type of 'it' is T = Object

Try here on TS Playground

您可以通过将 this 参数添加到 let 函数并从 let 调用中捕获 this 来执行此操作:

interface Object {
  let: <S, T>(this: T,  block: (thisVal: T) => S) => S | null
}

Object.prototype.let = function <S, T>(this: T,  block: (thisVal: T) => S): S | null {
  return this != null ? block(this as T) : null
}

const a = {foo: 42}
a.let(it => console.log(it.foo));

Playground Link