Dynamic return type based on array of keys inputted to function

Dynamic return type based on array of keys inputted to function

When working with TypeScript, it is common to come across situations where you need to dynamically determine the return type of a function based on an array of keys. This can be particularly useful when dealing with complex data structures or when writing generic utility functions. In this blog post, we will explore multiple solutions to this problem.

Solution 1: Using a mapped type

One way to achieve dynamic return types based on an array of keys is by using a mapped type. TypeScript provides a utility type called ReturnType which can be used to extract the return type of a function. By combining this with a mapped type, we can dynamically determine the return type based on the input keys.

type Data = {
  foo: string;
  bar: number;
  baz: boolean;
};

function pickKeys(keys: T[]): Pick {
  return keys.reduce((acc, key) => {
    acc[key] = data[key];
    return acc;
  }, {} as Pick);
}

const keys = ["foo", "bar"];
const result = pickKeys(keys);

console.log(result.foo); // string
console.log(result.bar); // number

Solution 2: Using a conditional type

Another approach is to use a conditional type to dynamically determine the return type based on the input keys. This can be achieved by using the keyof operator and a conditional statement to check if the input key exists in the data structure.

type Data = {
  foo: string;
  bar: number;
  baz: boolean;
};

type PickKeys = {
  [P in K]: T[P];
};

function pickKeys(keys: T[]): PickKeys {
  return keys.reduce((acc, key) => {
    if (key in data) {
      acc[key] = data[key];
    }
    return acc;
  }, {} as PickKeys);
}

const keys = ["foo", "bar"];
const result = pickKeys(keys);

console.log(result.foo); // string
console.log(result.bar); // number

Conclusion

Dynamic return types based on an array of keys can be achieved in TypeScript using mapped types or conditional types. Both solutions provide a way to extract specific properties from a data structure based on the input keys. Depending on your specific use case, you can choose the solution that best fits your needs.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *