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

前端 未结 1 891
栀梦
栀梦 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 from
    this answer to: How to get argument types from function in Typescript.

    Here's how:
    Demo on TypeScript playground

    type ArgumentTypes =
        F extends (...args: infer A) => any ? A : never;
    
    type Props> =
        Params extends { length: 0 } ?
        {
            fetcher: F;
        } : {
            fetcher: F;
            params: Params
        };
    
    function runTest(props: Props) { }
    
    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)
提交回复
热议问题