【问题标题】:Is it possible to extract function parameters types from object as tuples?是否可以从对象中提取函数参数类型作为元组?
【发布时间】:2019-04-23 05:14:58
【问题描述】:

例如我有一些带有函数的对象

{
 fnNumber: (x: number) => x,
 fnString: (x: string) => x
}

我想创建这种类型

{ 
  fnNumber: number,
  fnString: string
}

我可以这样做

type FnParam<T> = {[key in keyof T ]: T[key]}
type FnObject<T> = {[key in keyof T]: (x: T[key]) => any}

export function create<T>(x: FnObject<T>): FnParam<T> {
 return {} as any
}

const types = create({
 fnNumber: (x: number) => x,
 fnString: (x: string) => x
})
types: : {fnNumber: number, fnString: string}

但是如果函数有多个参数

{
 fnNumber: (x: number, y: string) => x,
 fnString: (x: string) => x
}

我需要创建元组

{ 
  fnNumber: [number, string],
  fnString: [string]
}

类似的东西

type FnParam2<T> = {[key in keyof T ]: T[key]}
type FnObject2<T> = {[key in keyof T]: (...x: T[key]) => any}

export function create2<T>(x: FnObject2<T>): FnParam2<T> {
 return {} as any
}

但是打字稿不能从...x: T[key]推断元组

有可能吗?

【问题讨论】:

    标签: typescript mapped-types


    【解决方案1】:

    顺便说一句,对于您的单参数版本,您不需要FnParams,您可以只使用T。这将产生相同的结果:

    export function create<T>(x: FnObject<T>): T {
     return {} as any
    }
    
    const types = create({
     fnNumber: (x: number) => x,
     fnString: (x: string) => x
    })
    // types: : {fnNumber: number, fnString: string}
    

    对于多个参数,您将需要使用conditional types 来提取参数(这只有在引入Tuples in rest parameters and spread expressions 之后的Typescript 3.0 或更高版本中才有可能)。

    type ArgumentTypes<T> = T extends (...a: infer A) => void ? A : never 
    type FnParam<T> = { [key in keyof T]: ArgumentTypes<T[key]> }
    type FnObject<T> = Record<string, (...a: any[]) => any>
    
    export function create<T extends FnObject<any>>(x: T): FnParam<T> {
        return {} as any
    }
    
    const types = create({
        fnNumber: (x: number, y: string) => x,
        fnString: (x: string) => x
    })
    
    types.fnNumber // [number, string]
    types.fnString // [string]
    

    【讨论】:

      猜你喜欢
      • 2013-01-16
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-04
      • 2019-03-02
      相关资源
      最近更新 更多