类型不同的打字稿界面

时间:2020-02-13 14:51:07

标签: javascript typescript

我有一个这样的自定义钩子,我想使请求参数为可选,并需要响应:

function useRequest<T, S = any>(api: (input?: S) => Promise<T>) {
  const [response, setResponse] = useState<T | null>(null);

  const fetchData = useCallback(
    (input?: S) => {
      api(input)
        .then((data) => {
          setResponse(data as T);
        })
    },
    [api],
  );
  return { response, fetchData };
}

基本上我想这样叫useRequest

function A()
{
  //return a promise
}
function B(p1: boolean) {
  //return a promise
}

useRequest<ResponseA>(A)
useRequest<ResponseB, boolean>(B)

但是我不能使用第二个,因为booleanboolean | undefined不兼容。

1 个答案:

答案 0 :(得分:2)

您不必将自己局限于一个参数,使用tuples in rest parameters可以捕获参数的类型并将其散布到新函数中。这样做的结果是保留了该函数的所有参数:

import { useState, useCallback} from 'react'

function useRequest<T, P extends any[]>(api: (...params: P) => Promise<T>) {
  const [response, setResponse] = useState<T | null>(null);

  const fetchData = useCallback(
    (...params: P) => {
      api(...params)
        .then((data) => {
          setResponse(data as T);
        })
    },
    [api],
  );
  return { response, fetchData };
}


type ResponseA = { a: string }
type ResponseB = { b: string }
declare function A(): Promise<ResponseA>;
declare function B(p1: boolean): Promise<ResponseB>;

useRequest(A)
useRequest(B)

Playground Link