function Container({sum, logMessage, doSomething}: ButtonProps,name :string) {
console.log(sum(10, 15));
logMessage('hello world');
doSomething('abc');
return <div>Hello world</div>;
}
const App = () => {
const sum = (a: number, b: number) => {
return a b;
};
const logMessage = (message: string) => {
console.log(message);
};
return (
<div>
<Container sum={sum} logMessage={logMessage} doSomething={logMessage} name = {"kasun"}/>
</div>
);
};
export default App;
On the above code I created two components(Container Component(Child), App Component (Parent)) and tried to pass two parameters to child component.But it gives the following error.
The "Property does not exist on type '{}'" error
CodePudding user response:
This looks like maybe a typescript error related to how you're defining the props type for Container here:
function Container({sum, logMessage, doSomething}: ButtonProps,name :string)
I think removing the ,name :string
part will probably get rid of that error but then of course you need to make sure that ButtonProps actually defines all of the props that you're accessing.
If you were wanting to add the name
prop you can do that like this:
function Container({sum, logMessage, doSomething}: ButtonProps & {name: string}) =>
Documentation on intersection and union types can be found here.
CodePudding user response:
Props flow through a single object.
Extend ButtonProps
with your additional props and use that compound type.
interface ContainerProps extends ButtonProps {
name: string
}
function Container({sum, logMessage, doSomething, name}: ContainerProps) {
// ...
}
CodePudding user response:
Props flow through a single object.
- In the container component, you are expecting an object and a string, where the object is destructed into sum, logMessage and doSomething. so it should look like this:
type ButtonProps = {
data: {
sum: (a, b) => number;
logMessage: (message) => void;
doSomething: (message) => void;
}
name: string;
};
function Container({{ sum, logMessage, doSomething }, name }: ButtonProps) {
console.log(sum(10, 15));
logMessage('hello world');
doSomething('abc');
return <div>Hello world</div>;
}
const App = () => {
const sum = (a: number, b: number) => {
return a b;
};
const logMessage = (message: string) => {
console.log(message);
};
return (
<div>
<Container data={sum, logMessage, doSomething} name = {"kasun"}/>
</div>
);
};