Home > front end >  Typescript - Convert from Array of types to Object of types
Typescript - Convert from Array of types to Object of types

Time:02-10

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 ?

CodePudding user response:

It has to be passed in as an array unfortunately because an object is a different type than an array.

type Sample = [a: string, b: number]
type Sample2 = { a:string, b:number}

function example(otherFunctionParameters: Sample){}
function example2(otherFunctionParameters: Sample2){}

example(['b', 3])
example2({a: 'b', b: 2})

I recommend changing the signature type of the calling function. If this is not possible, an array should work just fine.

CodePudding user response:

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
}

  •  Tags:  
  • Related