Home > Software engineering >  Convert Array Type into Object or Object type into Callback
Convert Array Type into Object or Object type into Callback

Time:08-30

I am currently working on one Project where I have one Object type something like below

type MyObject = {
  one: string;
  two: number;
  three: boolean;
}

and this is used in many places in my project but with different approach something like below

type MyCallback = (one: string, two: number, three: boolean) => void

so I want type in some way that I can write one thing and automatically second thing is converted.

What I tried

I try to convert Callback into Object because its looks easy

type CallbackArray = Parameters<MyObject> // results: [one: string, two: number, three: boolean]

Now I tried to convert this array into an Object something like below but I didn't get the desired output, don't know why ;_;

type ConvertArrayIntoObject<T extends any[]> = {
  [Key in keyof T]: T[key]
}

So Can someone please help me to findout what the problem is or give me an approach of the conversion of Array type into Object or Object type to Callback?

CodePudding user response:

If you would consider a refactor, it would involve making changes in the codebase from this:

type MyObject = {
  one: string;
  two: number;
  three: boolean;
}

type MyCallback = (one: string, two: number, three: boolean) => void

To this:

type MyObject = {
  one: string;
  two: number;
  three: boolean;
}
type MyCallback = (props: MyObject) => void

CodePudding user response:

You could define your "base" type in the following format:

type Base = [
  ["one", string], 
  ["two", number], 
  ["three", boolean]
]

This guarantees that bother order and names are known.

The format can now be converted to both object and function types.

type ToObject<B extends any[]> = {
  [I in B[number] as I[0]]: I[1]
}

type ToCallback<B extends any[]> = 
  (...args: [...{ [I in keyof B]: B[I][1] }]) => any

The resulting types would like like this:

type MyObject = ToObject<Base>
// type MyObject = {
//     one: string;
//     two: number;
//     three: boolean;
// }

type MyCallback = ToCallback<Base>
// type MyCallback = (args_0: string, args_1: number, args_2: boolean) => any

Structurally, these types are identical to the types you want to have. There is no programmatical way to create named tuples. That is why the names of the parameters in the callback are just args_0, args_1, ...

Playground

  • Related