【发布时间】:2021-05-19 20:45:50
【问题描述】:
我正在尝试设置一个接口,我可以在其中传递参数而无需指定其类型。
// Wrapper.tsx
interface Props extends MenuProps, ChakraProps {
handleTagClick: <T>(args?: T) => void
}
export const Wrapper: FC<Props> = ({ handleTagClick }): JSX.Element => {
return(
<Button
{...(
handleTagClick && {
onClick: () => handleTagClick({ ...dummyQuestion, type }) })
}
/>
)
}
然后我调用错误出现的那个组件:
export const Container = () => {
const { addNewThing } = useMyHook()
// The error comes from this line
return <Wrapper handleTagClick={addNewThing} />
}
错误:
Type '(question: VariableConfig) => void' is not assignable to type '<T>(args?: T | undefined) => void'.
Types of parameters 'question' and 'args' are incompatible.
Type 'T | undefined' is not assignable to type 'VariableConfig'.
Type 'undefined' is not assignable to type 'VariableConfig'.
Wrapper.tsx(10, 3): The expected type comes from property 'handleTagClick' which is declared here on type 'IntrinsicAttributes & Partial<Props> & { children?: ReactNode; }'
我做错了什么?
【问题讨论】:
-
错误是泛型函数类型接受
undefined作为参数类型,但您尝试传递给它的函数不接受,这是不兼容的。 -
可能的快速修复:
<T>(args: T) => void,因为您永远不会使用 undefined(没有任何参数)调用它。 -
@EmileBergeron 同样的错误:
Type '(question: VariableConfig) => void' is not assignable to type '<T>(args: T) => void'. Types of parameters 'question' and 'args' are incompatible. Type 'T' is not assignable to type 'VariableConfig'. -
请考虑修改此处的代码以构成minimal reproducible example 适合放入像The TypeScript Playground 这样的独立IDE 中,以便其他人可以自己演示您的问题(并且只有您的问题)。这允许其他人着手解决问题,而不是首先需要重新创建问题。我在这里强烈怀疑你需要
Props是通用的,而不是handleTagClick,但是如果没有我可以玩的例子,我不想冒险猜测实际答案。 -
我正在考虑它,然后意识到实际上没有直接的解决方案,因为它没有任何意义。在您的情况下,看起来您已经知道通用包装器中的类型(或类型的一部分),因为
handleTagClick({ ...dummyQuestion, type })显式传递了一个参数,您可能会想出一些通用类型来扩展。否则,如果它真的是可选的并且事先未知,那么泛型就没有意义,它可能应该是handleTagClick: (args?: any) => void。
标签: javascript reactjs typescript ecmascript-6