Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do objects narrow types correctly

When I use keyof to identify the parameters of function, its return value does not narrow the parameter correctly

typescript playground

const map = {
  foo: (a: number) => a,
  bar: (a: number, b: number) => a + b,
};

function fn(key:keyof typeof map) {
  return map[key];
}

// Error: Expected 2 arguments, but got 1.
fn('foo')(1);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to make the function generic so that the type of the argument passed to the function gets reflected in the return type that TypeScript can infer.

const map = {
  foo: (a: number) => a,
  bar: (a: number, b: number) => a + b,
};

function fn<T extends keyof typeof map>(key: T) {
  return map[key];
}

fn('foo')(1);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading