簡體   English   中英

在打字稿泛型類型聲明中遇到問題

[英]Having trouble in typescript generic type declaration

我正在創建一個名為useUpdate的鈎子,在聲明類型時遇到問題,代碼如下所示

type CallBack<T extends readonly any[]> = (
  ...args: T
) => void | (() => void | undefined);

function useUpdate<T extends readonly any[]>(
  callback: CallBack<T>,
  deps: T
) {
  const didMount = useRef(false);
  const prevDeps = useRef(deps);

  useEffect(() => {
    if (!didMount.current) {
      didMount.current = true;

      return;
    }

    const clean = callback(...prevDeps.current);

    prevDeps.current = deps;

    return () => {
      if (clean) {
        clean();
      }
    };
  }, deps);
}

使用時如果回調有args沒有問題,但是如果回調沒有提供args,則deps的類型會不正確

const state: boolean = useSomethingElse(); // get changable data from anywere else

// OK, no type error
useUpdate((prevState) => {
 console.log('I want to compare the current state and prevState', prevState, state);
},[state]);


useUpdate(() => {
 console.log('I only care about the current state', state);
},[state]); // Type error occurs on this line, the message is:
//  Argument of type '[boolean]' is not assignable to parameter of type '[]'.
//  Source has 1 element(s) but target allows only 0.ts(2345)

我知道這是因為 TypeScript 將 T 設置為回調參數,如果未提供參數,則為 [],但是有沒有辦法讓 TypeScript 在設置 T 時使用 deps 的類型並跳過回調參數的類型?

有兩種方法可以解決此問題:

(1) 使deps成為第一個參數,因此它首先從deps推斷T

(2) 對callback使用第二個泛型:

function useUpdate<T extends readonly any[], Cb extends CallBack<T>>(
  callback: Cb,
  deps: T
) {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM