DmitriyC
DmitriyC

Reputation: 43

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

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

I don't want to pass an array in the parameter.

How can I achieve this ?

Upvotes: 3

Views: 1224

Answers (1)

jsejcksn
jsejcksn

Reputation: 33691

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.

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:

TS Playground

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
}

Upvotes: 1

Related Questions