繁体   English   中英

TypeScript:推断类型<this>在 Object 扩展方法中</this>

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

我正在尝试实现类似于 kotlin 中的 scope function的东西

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

有没有办法推断调用 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

在 TS Playground 上试试

您可以通过将this参数添加到let function 并从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));

游乐场链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM