TypeScript泛型:从函数参数推断键值返回类型的键

时间:2018-07-30 19:39:34

标签: typescript generics typescript-generics

我必须执行以下功能:

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

我想摆脱(或省略)K extends string = string部分。

此刻,我必须这样称呼它:

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

但是我不想两次输入foo。我只想这样使用它:

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

尽管理想情况下,我想这样输入函数:

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

这有可能吗?

1 个答案:

答案 0 :(得分:1)

在3.1中可能会使用this page推断一些类型参数。

在此之前,您可以让该函数返回另一个函数,其中第一个调用指定第一个类型参数,第二个调用指定其余类型

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

x<string>()('foo')
相关问题