首页 > 解决方案 > Untyped function calls may not accept type arguments error on generic custom hook

问题描述

I am using this generic hook to return previous props, it was working fine but all of a sudden it is giving "Untyped function calls may not accept type arguments." error.

function usePrevious<T>(value: T): T | undefined {
    const ref = useRef<T>();
    useEffect(() => {
        ref.current = value;
    });
    return ref.current;
}

const TestingContainer: React.FC<Props> = (props) => {
    ...
    usePrevious<Props>(props)
    ...
}

标签: javascriptreactjstypescript

解决方案


你必须给props参数Props类型

请参阅下面的 LIVE 示例或代码

/**
 * stubs - start
*/
interface Props {
    someProp: string;
}

interface MutableRefObject<T> {
    current: T;
}

function useRef<T>(initialValue: T): MutableRefObject<T>;

function useRef<Props>() {
    return mutObj;
}

const mutObj: MutableRefObject<Props> = {
    current: {
        someProp: '123',
    },
}


/**
 * stubs - end
*/

function usePrevious<T>(value: T): T | undefined {
    // in order to pass validations in this playground
    const ref = useRef<T>(value);

    // in order to pass validations in this playground
    /* useEffect(() => {
        ref.current = value;
    }); */

    return ref.current;
}

const TestingContainer = (props: Props) => {
    usePrevious<Props>(props)
}

请让我知道它是否适合您)


推荐阅读