user15163984
user15163984

Reputation: 534

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);

Upvotes: 1

Views: 52

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

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);

Upvotes: 2

Related Questions