【问题标题】:Explicit on first generic but infer the second in TS? [duplicate]在第一个泛型上显式但在 TS 中推断出第二个? [复制]
【发布时间】:2019-08-12 05:35:26
【问题描述】:

是否可以在第一个泛型上显式,但在第二个泛型上隐式(推断)?

例如一个pick函数:

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

【问题讨论】:

    标签: typescript typescript-typings typescript-generics


    【解决方案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');
    

    你可以通过柯里化函数;让我知道这是否有帮助

    【讨论】:

    • 是的,就是我一起去的那个。不幸的是,正如我所读到的,到目前为止还没有适合部分推理的解决方案:/。感谢您的回答!
    猜你喜欢
    • 2011-10-11
    • 2021-11-11
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    相关资源
    最近更新 更多