I have a code similar to this:
const x = 'a';
const y = 1;
const arr1 = [x, y]; // -> (string | number)[]
const arr2: [string, number] = [x, y]; // -> [string, number]
I cant understand why TypeScript's type inference is getting (string | number)[] instead of [string, number].
Do I have to specifically tell TypeScript arr2: [string, number] or maybe there is easier way?
Above example is simple, but problem is more annoying with this:
function useFormField() {
const [field, setField] = useState('');
const [fieldError, setFieldError] = useState(false);
const fieldRef = useRef<HTMLInputElement>(null);
return [field, setField, fieldError, setFieldError, fieldRef];
}
Type inference: (string | boolean | React.RefObject<HTMLInputElement> | React.Dispatch<React.SetStateAction<string>> | React.Dispatch<React.SetStateAction<boolean>>)[]
So to make it what I need I have to define return type manually:
function useFormField(): [string, React.Dispatch<React.SetStateAction<string>>, boolean, React.Dispatch<React.SetStateAction<boolean>>, React.RefObject<HTMLInputElement>]{
// ...
}