简体   繁体   English

Typescript - 从类型数组转换为 Object 类型

[英]Typescript - Convert from Array of types to Object of types

I need this type我需要这种类型

type Sample = [a: string, b: number]

to be converted to转换成

type Sample2 = { a:string, b:number}

I need this to pass arguments of a function in a paramenter, in form of an object我需要这个以 object 的形式在参数中传递 function 的 arguments

function example(otherFunctionParameters: Parameters<typeof otherFunction>){}

I don't want to pass an array in the parameter.我不想在参数中传递数组。

How can I achieve this?我怎样才能做到这一点?

Because you can't manipulate tuple labels in the type system , the best you can do is manually supply a tuple of property keys, one for every parameter in the original function.因为你不能在类型系统中操作元组标签,你能做的最好的就是手动提供一个属性键的元组,一个用于原始 function 中的每个参数。

By adapting some utilities from this answer by jcalz, here's a generic utility that will give you a mapped object for the parameters in a function: You supply the function type and a tuple of labels for each parameter:通过从 jcalz 的这个答案中改编一些实用程序,这里有一个通用实用程序,它将为 function 中的参数提供映射的 object:您为每个参数提供 function 类型和标签元组:

TS Playground TS游乐场

type ZipTuples<Keys extends readonly any[], Values extends readonly any[]> = {
  [K in keyof Keys]: [Keys[K], K extends keyof Values ? Values[K] : never];
};

type ZipTuplesAsObject<
  Keys extends readonly PropertyKey[],
  Values extends readonly any[],
> = { [T in ZipTuples<Keys, Values>[number] as T[0]]: T[1] };

type ParamsAsObject<
  Fn extends (...params: readonly any[]) => any,
  Keys extends readonly PropertyKey[],
> = ZipTuplesAsObject<Keys, Parameters<Fn>>;


// Use

declare function otherFunction (
  irrelevantLabel: string,
  alsoNotUsed: number,
  onlyTheTypesMatter: boolean,
): void;

function example (objectParam: ParamsAsObject<typeof otherFunction, ['a', 'b', 'c']>) {
  // objectParam; // { a: string; b: number; c: boolean; }
  const {a, b, c} = objectParam;
  a; // string
  b; // number
  c; // boolean
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM