示例一
type Foo = (this: string, hasChildren: boolean) => void
type Bar<T> = T extends (this: infer P, ...args: infer U) => void ? P : unknown
type Baz = Bar<Foo> // Baz得到的是 Foo参数中this的类型string
示例二
type Foo = (this: string, hasChildren: boolean) => void
type Bar<T> = T extends (...args: infer U) => void ? U : unknown
type Baz = Bar<Foo> // Baz得到的是 hasChildren的类型boolean [boolean]
这两个例子中Bar都是获取函数中参数类型
为什么实例二中args中没有包含this类型,Baz的类型为什么不是 [string, boolen],而是[string]?
this
不是参数名呀,this
是函数的上下文。Foo
函数的参数是[hasChildren]
,对应的类型是[boolean]
。上下文是string
。示例一中,
this: infer P
,获取的是上下文类型,所以Baz
是string
。示例二中,没有特别指定上下文,
...args: infer U
,获取的是参数类型,所以Baz
是[boolean]
。