提取通用函数中的键类型

时间:2019-06-14 11:06:51

标签: typescript generics

是否可以从T函数类型中提取<K extends keyof T>(k: K) => T[K]类型

type T = { a: 'a'; b: 'b' }
type Fn = <K extends keyof T>(k: K) => T[K]

// This results in the return types being 'any'
type ValueOfT = Fn extends (k: keyof infer U) => any ? U : never


// This throws a compiler error
type ValueOfT2 = Fn extends <K extends keyof infer U>(k: K) => U[K]
  ? U
  : never


// Type isn't narrowed
type NotNarrowed = Fn extends (k: 'a') => infer U ? U : never
// so can't do this
type FnTypes = Fn extends (a: infer U) => any ? U : never
type ValueOfT3 = { [K in FnTypes]: Fn extends (a: K) => infer U ? U : never }


0 个答案:

没有答案