Reputation: 1551
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?
Upvotes: 19
Views: 28453
Reputation: 1
let a = 6;
let b = 2;
let res = outer(substr, a, b);
console.log(res);
res = outer(addit, a, b);
console.log(res);
function outer(inner: Function, a: number, b: number): number {
return inner(a,b);
}
function substr(vala: number, valb: number): number {
console.log('We are substracting');
return vala - valb;
}
function addit(vala: number, valb: number): number {
console.log('We are adding');
return vala + valb;
}
Upvotes: 0
Reputation: 4194
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
Upvotes: 20
Reputation: 14669
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;}
).
Upvotes: 4