[Typescript] Pick partially object type with indexed access types

type PartOfWindow = {
    [Key in 
      | "document"
      | "navigator"
      | "setTimeout"]: Window[Key]
}
/*
type PartOfWindow = {
    document: Document;
    navigator: Navigator;
    setTimeout: (handler: TimerHandler, timeout?: number | undefined, ...arguments: any[]) => number;
}
*/

 

We can refacotr the type to be more generalic

type PickWindowProperties<Keys extends keyof Window> = {
  [Key in Keys]: Window[Key]
}

type PartOfWindow = PickWindowProperties<"document" | "navigator" | "setTimeout">

 

Further:

type PickProperties<
  ValueType,
  Keys extends keyof ValueType
> = {
  [Key in Keys]: ValueType[Key]
}

type PartOfWindow = PickProperties<
  Window,
  "document" | "navigator" | "setTimeout"
 >

 

This is how Pick works:

/**
 * From T, pick a set of properties whose keys are in the union K
 */
type Pick<T, K extends keyof T> = {
  [P in K]: T[P]
}

 

posted @ 2022-08-18 19:16  Zhentiw  阅读(18)  评论(0编辑  收藏  举报