1

I'm looking for a way to make Typescript guess the return type of my function according to the function arguments.

function fn<T extends object>(a: T, b: T, property: keyof T): any {
  return a[property] ?? b[property];
}

I want to remove any to get the proper return type.

interface A {
  foo?: string;
}

const a: A = { foo : 'bar' };
const b: A = {};
const a = fn(a, b, 'foo'); // it should get the string type from inference

I looked at ReturnType<T> by using it like this ReturnType<typeof T[property]> but it seems not supported by Typescript. I don't known if it's feasible?

1 Answer 1

2

Add another type parameter for the property name:

function fn<T, K extends keyof T>(a: T, b: T, property: K): T[K] {
  return a[property] ?? b[property];
}

Note that it will infer string | undefined, not string, because the foo property on the interface A is optional, so it's possible both a and b don't have it.

Playground Link

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.