Home > Back-end >  TypeScript: return type for method with variable structure
TypeScript: return type for method with variable structure

Time:12-14

I have a method which accepts a array of properties of an object and returns an object with a given shape:

// sample class
class T {
  propA: number;
  propB: string;

  method() {}

}


function myMethod(obj: any, properties: string[]): MyMethodReturnType {
   // implementation
}

const obj = new T();

const result = myMethod(obj, ['propA', 'propB'])

// result will be the following:
{
 propATrigger: NotRelevantType;
 propBTrigger: NotRelevantType;
}

--> So myMethod returns an object containing key-value pairs for all properties passed in the array of keys, postfixed with "Trigger"

My question is: How would the return type MyMethodReturnType of myMethod look like?

CodePudding user response:

You can use this (playground link):

function myMethod<T extends ReadonlyArray<string>>(obj: any, properties: T): {
    [prop in T[number] as `${prop}Trigger`]: boolean
} {
   // implementation
   return {} as any
}

const result = myMethod({}, ['propA', 'propB'] as const)
const x = result.propATrigger
const y = result.propBTrigger
const fails = result.propA

With { [prop in T[number]]: any } you can create an object with the keys of the array T. By using template literal types you can add Trigger to the end of these keys.

  • Related