Home > OS >  Typescript function that returns modified object with correct types
Typescript function that returns modified object with correct types

Time:07-20

this might sound stupid but I want to know If I can use a function that returns a modified object and display the correct type in return.

The input is as followings

{
  enable: { label: "Enable", value: false },
  castShadow: {
           label: "Intensity",
           value: 25,
           condition: currentValue.type === "Circle"}
}

As for the return value, I want to modify it to be just like this

{enable:true,castShadow:40}

To final goal I want to achieve is this one if it is possible

  const { ConfigRenderer, enable, castShadow} = useConfig({
        enable: { label: "Enable", value: false },
         castShadow: {
           label: "Intensity",
           value: 25,
           condition: currentValue.type === "Circle"}
  });

CodePudding user response:

You can achive this using mapped types and conditional types like this:

type ValuesOf<T, P = 'value'> = { 
   [K in keyof T]: P extends (keyof T[K]) ? T[K][P] : never 
};

function useConfig<T>(param: T): ValuesOf<T> {
   // ...
}

The ValuesOf type is a mapped type that will contain all keys of type T but maps them to the type of the property P inside type T (or to never, if property P does not exist on type T). In the code above P is defaulted to 'value' but you could as well use any other property name or even a union of property names.

  • Related