I understand this ts error (TS2349) appears because of not consistent type in the return tuple. But is it the right way to manage this error by adding 'as const' on custom hook's return value?
// useCustomHook.tsx
import { useState, useEffect } from "react";
export default (key: string, initValue: string = '') => {
const [value, setValue] = useState(() => localStorage.getItem(key) || initValue)
useEffect(() => { localStorage.setItem(key, value) }, [key, value]);
return [value, setValue] as const; // without 'as const' =>
// TypeScript error TS2349 on hook calls
}
// Component.tsx
import React, { useState, useEffect } from 'react';
import useCustomHook from 'components/hooks/useCustomHook';
const Component = () => {
const [someKey, setSomeKey] = useCustomHook('some_key');
useEffect(() => {
setSomeKey('value'); // without 'as const' in custom hook it fails to compile:
// This expression is not callable.
// Not all constituents of type
// 'string | Dispatch<SetStateAction<string>>'
// are callable. Type 'string' has no call signatures.
}, [setSomeKey]);
return (
<>{someKey}</>
)
}
n.b. "react" : "^16.13.1" "typescript": "~3.7.2"