Linked Questions

Popular Questions

TypeScript - inferring or declaring Pick type as a functions return value

Asked by At

Considering the following simplified function, which accepts an object and a property of that object, and returns a clone of that object with only the specified property:

export function clonePick<T, K extends keyof T>(obj: T, prop: K) {
  const keys = Object.keys(obj).filter(k => k === prop)
  return keys.reduce(
    (clone: any, key: string) => {
      return { ...clone, [key]: obj[key as keyof T] };

This is essentially identical behavior to Pick except for a value instead of a type, and so it's return type could be expressed as:

Pick<T, prop>

Except the above is not valid typescript. However, we can know the value of prop well before runtime when calling the function:

interface ITest {
  numProp: number;
  strProp: string;

const test = { numProp: 1, strProp: '1' }; // <-- type is ITest

const testClone = clonePick(test, 'numProp') // <-- type is any

I can easily declare this explicitly:

const testClone: Pick<ITest, 'numProp'> = clonePick(test, 'numProp')

But it would be a lot more maintainable if I could include that behavior as part of the above function. Is this possible? Preferably it can work with an array of properties as well as a single prop

Related Questions