'Typescript not accepting interface params
In the following code the compiler is throwing error:
Expected 1 arguments, but got 3.
Can anyone explain whats wrong and what needs to be changed? I have other interface based functions that are working fine, but this function doesnt seem to be acknowledging the interface properties.
Code:
interface withTitleComponentProps {
component: Injectable<ReactElement> | ReactElement;
title: string | null | undefined;
isComponent?: boolean;
}
export const withTitleComponent = (props: withTitleComponentProps): React.ComponentType => {
let {component, title, isComponent} = props
if (isComponent) {
return titleComponent({
NewComponent: withInjectedProps(component as Injectable<ReactElement>),
title: title,
});
} else {
return titleElement({
NewComponent: component as ReactElement,
title: title,
});
}
};
Solution 1:[1]
In your comment you say you are calling this function like:
withTitleComponent( LandingScreen, null, true)
However, you only declare that with one argument:
export const withTitleComponent = (props: withTitleComponentProps): React.ComponentType => {
Since withTitleComponentProps is a type that has properties, did you mean to pass in an object with those properties?
withTitleComponent({
component: LandingScreen,
title: null,
isComponent: false,
})
Alternatively, declare it with three arguments:
export const withTitleComponent = (
component: Injectable<ReactElement> | ReactElement;
title: string | null | undefined;
isComponent?: boolean;
): React.ComponentType => {}
withTitleComponent(LandingScreen, null, true)
Or use a tuple (as suggested by @youdateme)
type withTitleComponentProps = [
component: Injectable<ReactElement> | ReactElement,
title: string | null | undefined,
isComponent?: boolean,
]
export const withTitleComponent = (...args: withTitleComponentProps): React.ComponentType => {}
withTitleComponent(LandingScreen, null, true) // works
Just note that this is not an object with 3 properties. It is a fixed length array with three element.
Solution 2:[2]
Use a tuple type
[component: ..., title: ..., isComponent?: ...]and then in the function define it as(...args: MyTupleType) => ...
Example:
type WithComponentTitleProps = [
component: Injectable<ReactElement> | ReactElement,
title: string | null | undefined,
isComponent?: boolean,
];
const withComponentTitle = (...args: WithComponentTitleProps) => ...
Then you can reuse the type anytime you wish to have the same parameters as withComponentTitle
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | hittingonme |
