typescript - 明确第一个泛型,但在 TS 中推断第二个泛型?

标签 typescript typescript-typings typescript-generics

是否可以明确第一个泛型,但隐式(推断)第二个泛型?

例如选择函数:

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/

相关文章:

javascript - 在 Angular rxjs 中寻找类似 OrElse 的东西在管道时查找函数

javascript - 如何让 TypeScript 提示字符串与其他类型的连接?

typescript - 根据 Typescript 中多个对象的同名属性创建对象类型?

typescript - 无法使 TypeScript 泛型链工作

typescript - TypeScript 类型中的组选项

typescript - 如果函数声明时没有 `const` 关键字,函数调用签名会出错

html - mat-table 不会被来自restservice 的数据填充

typescript - 如何一般地键入返回对象数组的值数组的函数?

如果将泛型用作回调的参数,则 TypeScript 泛型的类型推断会失败

typescript - 我可以在 juxt 函数中使用映射元组类型吗?