I am trying to pass in this doSomething
function into performAction
, but the error I'm getting is Expected 0 arguments, but got 1
type someType = {
name: string,
id: string
}
function doSomethingFn(props: someType) {
console.log(props.name + " " + props.id);
}
function performAction(doSomething: () => void) {
doSomething({
name: "foo",
id: "bar"
});
}
performAction(doSomethingFn);
Am I using the proper syntax for Typescript?
In TypeScript, the compiler checks every function call and issues an error in the following cases: The number of arguments is different from the number of parameters specified in the function. Or the types of arguments are not compatible with the types of function parameters.
Just like with function declarations, if a parameter type isn’t specified, it’s implicitly any. Note that the parameter name is required. The function type (string) => void means “a function with a parameter named string of type any “! Of course, we can use a type alias to name a function type: // ...
For example, if you make the b parameter optional, and c parameter required the TypeScript compiler will issue an error: error TS1016: A required parameter cannot follow an optional parameter.
A function type (note: this link redirects to old TypeScript docs, but it has a much clearer example than the newer ones) is made up of the types of the arguments the function accepts and the return type of the function. The above example, if implemented in JavaScript, would work fine and have no issues.
The doSomething
type seems incorrect. In the type declaration – () => void
it takes no arguments, but later you are passing arguments to it.
For this piece of code following would work, but you would know better what should be the arguments and their types of doSomething
. Probably use a interface if you already have an abstraction in your mind.
function performAction(doSomething: (stuff: { name: string, id: string }) => void) {
doSomething({
name: "foo",
id: "bar"
});
}
Demo for above.
Also if string
in your code is a variable you need to change that because string
is reserved for the type. In case you don't what to fix the type of doSomething
right now you can use the Function
type. Demo
For your updated question you need to write function performAction(doSomething: (stuff: someType) => void
Demo
You type doSomething as a function with no arguments: doSomething: () => void
. Make it, dunno, doSomething: (arg: SomeInterface) => void
(SomeInterface being, for example, {name: string; id: string;}
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With