reactjs中的通用类型

问题描述 投票:2回答:1

我为应用程序中的句柄输入编写了一个自定义钩子。我使用通用类型来定义自定义钩子返回的类型。这是我的代码

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>

这是我错了吗?请帮助我

javascript reactjs typescript
1个回答
2
投票

IUseInput<T, U>是函数的类型,而不是返回类型的类型。没有方法可以指定函数声明的类型,只能指定变量的类型(可以向其分配函数)。但是,这并不是必须的,我只需将返回类型从IUseInput移到函数声明中即可。

© www.soinside.com 2019 - 2024. All rights reserved.