Leonardo Silva Leonardo Silva - 3 years ago 174
TypeScript Question

typescript generic function index constraint

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.

Answer Source

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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download