Benjamin M
Benjamin M

Reputation: 24527

TypeScript Generics: infer key of key-value return type from function argument

I have to following function:

function x<V = string, K extends string = string>(myKey: K): {[k in K]: V} {
  return null as any;
}

I'd like to get rid (or omit) the K extends string = string part.

At the moment I have to call it like this:

const res = x<number, 'foo'>('foo');   // resulting type: { foo: number }

But I don't want to type foo twice. I simply want to use it like this:

const res = x<number>('foo');

Though ideally I'd like to type the function like this:

function x<V = string>(myKey: string): {[myKey]: V} {
  return null as any;
}

Is this somehow possible?

Upvotes: 3

Views: 507

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249546

It will be posibile in 3.1 to infer just some type arguments with Named type arguments & partial type argument inference.

Until then you can have the function return another function, with the first call specifying the first type parameter and the second inferring the rest

function x<V = string>() {
    return function <K extends string = string>(myKey: K): { [k in K]: V } {
        return null as any;
    }
}

x<string>()('foo')

Upvotes: 2

Related Questions