복붙노트

[REACTJS] 타이프 라이터는 반작용 : 조건부 옵션 소품 다른 소품의 유형에 따라

REACTJS

타이프 라이터는 반작용 : 조건부 옵션 소품 다른 소품의 유형에 따라

해결법


  1. 1.이 타이프 3.0에서 가능하다.

    이 타이프 3.0에서 가능하다.

    질문에 대답하기 위해, 나는에서 ArgumentTypes 를 사용 타이프에 함수에서 인수 형식을 얻는 방법 :이 대답.

    방법은 다음과 같습니다 타이프 라이터 놀이터 데모

    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]
    });
    
  2. from https://stackoverflow.com/questions/52771626/typescript-react-conditionally-optional-props-based-on-the-type-of-another-prop by cc-by-sa and MIT license