Typescript React: Conditionally optional props based on the type of another prop

前端 未结 1 881
栀梦
栀梦 2021-01-02 00:24

I\'m trying to type a fetcher component API that I\'m working on. The idea is quite simple, you give it a fetcher (promise returning function) and a param

相关标签:
1条回答
  • 2021-01-02 00:45

    This is possible in TypeScript 3.0.

    To answer the question, I used ArgumentTypes<F> from
    this answer to: How to get argument types from function in Typescript.

    Here's how:
    Demo on TypeScript playground

    type ArgumentTypes<F extends Function> =
        F extends (...args: infer A) => any ? A : never;
    
    type Props<F extends Function,
        Params = ArgumentTypes<F>> =
        Params extends { length: 0 } ?
        {
            fetcher: F;
        } : {
            fetcher: F;
            params: Params
        };
    
    function runTest<F extends Function>(props: Props<F>) { }
    
    function test0() { }
    function test1(one: number) { }
    
    runTest({
        fetcher: test0
        // , params: [] // Error
    });
    runTest({
        fetcher: test1
        // Comment it, 
        //  or replace it with invalid args
        //  and see error
        , params: [1]
    });
    
    0 讨论(0)
提交回复
热议问题