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

3

我正在尝试在TypeScript中实现类似于Kotlin的let作用域函数

我的当前方法是使用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

在TS Playground上试一试

1个回答

2
你可以通过向 let 函数添加 this 参数并从 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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接