0

is there a way to specify something that behaves as this suggests?

function fn<T, U extends keyof T, T[U] extends number>()

i cannot get "T[U] extends number" part to work.

1 Answer 1

1

How about this?

function fn<T extends Record<U, number>, U extends keyof T>(t: T, u: U): number {
  return t[u];
}

By saying that T extends Record<U, number> you are essentially saying that T[U] exists and is of type number (or some subtype):

fn({ name: 'fred', age: 40 }, 'age');  // okay
fn({ name: 'fred', age: 40 }, 'name');  // error
fn({ name: 'fred', age: 40 }, 'oops');  // error

Does that work for you?

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.