Typescript中关于Rest Parameter 和 This的问题

示例一

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]?

阅读 1.2k
1 个回答

this不是参数名呀,this是函数的上下文。
Foo函数的参数是[hasChildren],对应的类型是[boolean]。上下文是string
示例一中,this: infer P,获取的是上下文类型,所以Bazstring
示例二中,没有特别指定上下文,...args: infer U,获取的是参数类型,所以Baz[boolean]

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题