![](/img/trans.png)
[英]Can Typescript infer the type of an instance of an extension class instantiated by a method of its base?
[英]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
您可以通过将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.