是否可以明确第一个泛型,但隐式(推断)第二个泛型?
例如选择函数:
function pick<T extends { [K: string]: any }, U extends keyof T>(obj: T, key: U): T[U] {
return obj[key];
}
interface Obj {
foo: string;
bar: string;
}
const obj = {
foo: 'foo',
bar: 'bar',
};
// works, available keys are inferred
pick(obj, 'bar');
// error: Expected 2 type arguments, but got 1.
// Is there a way I can tell to TS to infer the 2nd generic instead of expecting it explicitly?
pick<Obj>(obj, '');
最佳答案
const pick = <T extends { [K: string]: any }>(obj: T) => <U extends keyof T>(key: U): T[U] => {
return obj[key];
}
interface Obj {
foo: string;
bar: string;
}
const obj = {
foo: 'foo',
bar: 'bar',
};
// works, available keys are inferred
pick(obj)(bar)
// error: Expected 2 type arguments, but got 1.
// Is there a way I can tell to TS to infer the 2nd generic instead of expecting it explicitly?
pick<Obj>(obj)('foo');
您可以通过柯里化(Currying)函数;让我知道这是否有帮助
关于typescript - 明确第一个泛型,但在 TS 中推断第二个泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57453443/