[英]typescript interface with different number of types
我有一個像這樣的自定義鈎子,我想讓請求參數可選並且需要響應:
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)
但我不能使用第二個,因為boolean
與boolean | undefined
boolean
不兼容boolean | undefined
boolean | undefined
。
您不必將自己限制為一個參數,在其余參數中使用元組,您可以捕獲參數的類型並將它們傳播回新函數。 這樣做的效果是保留了函數的元數:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.