显式使用第一个泛型,但推断TS中的第二个?

时间:2019-08-11 20:39:07

标签: 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, '');

1 个答案:

答案 0 :(得分:1)

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');

您可以通过使用该函数;让我知道这是否有帮助