我编写了一个自定义钩子来处理我的应用程序中的输入。我使用泛型类型来定义自定义钩子返回的类型。以下是我的代码
interface IUseInput<T, U> {
(): [T, (e: ChangeEvent<HTMLInputElement>) => void, U];
}
function useInput<T, U>(): IUseInput<T, U> {
const [input, setInput] = useState({});
const [isDirty, setDirty] = useState({});
const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
setInput({
...input,
[e.target.name]: e.target.value
});
setDirty({
...isDirty,
[e.target.name]: true
});
};
return [input, handleInputChange, isDirty] //this line get error
}
const Component: React.FC = () => {
const [input, handleChangeInput, isDirty] = useInput<{username: string, password: string}, {username: boolean, password: boolean}>();
return (
....
)
}
但是我得到了这个错误Type '{}[]' is not assignable to type 'IUseInput<T, U>
WHere是我的错吗?请帮帮我
发布于 2020-02-13 16:24:32
IUseInput<T, U>
是函数的类型,不是返回类型的类型。没有办法指定函数声明的类型,只能指定变量的类型(您可以将函数赋给该变量)。然而,这并不是真正必要的,我只是将返回类型从IUseInput
转移到函数声明。
由于U
应该与T
具有相同的键,因此可以进行改进,您可以使用预定义的映射类型Record
从T
派生U
。因此,您可以用Record<keyof T, boolean>
替换U
function useInput<T>(): [T, (e: ChangeEvent<HTMLInputElement>) => void, Record<keyof T, boolean>] {
const [input, setInput] = useState({} as T);
const [isDirty, setDirty] = useState({} as Record<keyof T, boolean>);
const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
setInput({
...input,
[e.target.name]: e.target.value
});
setDirty({
...isDirty,
[e.target.name]: true
});
};
return [input, handleInputChange, isDirty]
}
https://stackoverflow.com/questions/60211843
复制相似问题