網站搜尋

reactjs - 使用 TypeScript 的自定義 Hooks - 返回值


我正在嘗試用 TS(對兩者都相當新)實驗自訂 Hooks。這個 useOption 應該接受 number 或 boolean,並返回相同類型的 value 以及更改函數。這是因為一個選項應該是 'range' 類型的 <input>,而另一個 <input> 是複選框(但這可以擴展到其他輸入類型)。所以我有一個 <Options /> 元件如下:

const Options = () => {
  const [pieces, setPieces] = useOption(10);
  const [speed, setSpeed] = useOption(5);
  const [sound, setSound] = useOption(false);

  return (
    <div className='Options'>
      <input
        type='range'
        value={pieces}
        onChange={setPieces}
        min='5'
        max='25' />
      <p>{pieces}</p>
      <input
        type='range'
        value={speed}
        onChange={setSpeed}
        min='1'
        max='10' />
      <p>{speed}</p>
      <input
        type='checkbox'
        value={sound}
        onChange={setSound} />
      <p>{sound ? 'Sound on' : 'Sound off'}</p>
      <button
        className='start-btn'
        onClick={handleClick}>Start game</button>
    </div>
  )
};

以及一個自訂 hook useOption。

const useOption = (initialValue: number | boolean) => {
  const [value, setValue] = useState(initialValue);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (typeof(e.currentTarget.value) === 'boolean') {
      const newValue = !value;
      setValue(newValue);     
    } 
    else {
      const newValue = Number(e.currentTarget.value);
      setValue(newValue)
    }
  };

  return [value, handleChange] as const;
};

我以為,使用 typeof 型別保護和 const(像這頁面所寫),TS 可以辨識返回的型別,但我仍然收到關於它的錯誤,錯誤訊息顯示在 value 屬性上。

Type 'number | boolean' is not assignable to type 'string | number | readonly string[] | undefined'.
  Type 'false' is not assignable to type 'string | number | readonly string[] | undefined'.ts(2322)
index.d.ts(2256, 9): The expected type comes from property 'value' which is declared here on type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'

有關如何解決它有任何建議嗎?

答案#1

你可以使這個 hook 通用

const useOption = <T extends number | boolean>(initialValue: T) => {
  const [value, setValue] = React.useState(initialValue);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (typeof e.currentTarget.value === 'boolean') {
      const newValue = !value;
      setValue(newValue as T);
    } else {
      const newValue = Number(e.currentTarget.value);
      setValue(newValue as T);
    }
  };

  return [value, handleChange] as const;
};

並在組件中傳遞類型

export default function App() {
  const [pieces, setPieces] = useOption<number>(10);
  const [speed, setSpeed] = useOption<number>(5);
  const [sound, setSound] = useOption<boolean>(false);

  return (
    <div className="Options">
      <input
        type="range"
        value={pieces}
        onChange={setPieces}
        min="5"
        max="25"
      />
      <p>{pieces}</p>
      <input type="range" value={speed} onChange={setSpeed} min="1" max="10" />
      <p>{speed}</p>
      <input type="checkbox" checked={sound} onChange={setSound} /> // use checked in here
      <p>{sound ? 'Sound on' : 'Sound off'}</p>
    </div>
  );
}

示範