First of all, the problem I'm facing:
I worked a few months with a self made React Hook with vanilla JS, code bellow:
import { useState } from 'react';
const useForm = (initialValues) => {
const [state, setState] = useState(initialValues);
return [
state,
(e) => {
if (typeof e.target !== 'undefined') {
setState({
...state,
[e.target.name]: e.target.value,
});
} else {
setState({ ...e });
}
},
];
};
export default useForm;
Right now, I decided to go Typescript. However could not convert that hook. I got like everything in place but the return interface/type. Same hook Typescript version (with a wrong return type):
import { useState, FormEvent } from 'react';
interface ReturnProps {
[index: number]: Record<string, unknown>;
[index: number]: (e: FormEvent<HTMLInputElement>) => void;
}
const useForm = (initialValues: Record<string, unknown>): ReturnProps => {
const [state, setState] = useState(initialValues);
return [
state,
(e: FormEvent<HTMLInputElement>): void => {
if (typeof e.currentTarget !== 'undefined') {
setState({
...state,
[e.currentTarget.name]: e.currentTarget.value,
});
} else {
setState({ ...e });
}
},
];
};
export default useForm;
Question is: How to return the right type in this situation?
question from:
https://stackoverflow.com/questions/65890273/return-an-array-of-object-and-function-typescript 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…