我必须执行以下功能:
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;
}
这有可能吗?
最佳答案
在 3.1 中可以用 Named type arguments & partial type argument inference 推断一些类型参数.
在那之前你可以让函数返回另一个函数,第一个调用指定第一个类型参数,第二个调用推断其余的
function x<V = string>() {
return function <K extends string = string>(myKey: K): { [k in K]: V } {
return null as any;
}
}
x<string>()('foo')
关于TypeScript 泛型 : infer key of key-value return type from function argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51601151/