[英]Passing function as parameter in Typescript: Expected 0 arguments, but got 1.ts
I am trying to pass in this doSomething
function into performAction
, but the error I'm getting is Expected 0 arguments, but got 1
我试图将此doSomething
function 传递给performAction
,但我得到的错误是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?我是否对 Typescript 使用了正确的语法?
The doSomething
type seems incorrect. doSomething
类型似乎不正确。 In the type declaration – () => void
it takes no arguments, but later you are passing arguments to it. 在类型声明– () => void
它不接受任何参数,但是稍后您将参数传递给它。
For this piece of code following would work, but you would know better what should be the arguments and their types of doSomething
. 对于这段代码,可以使用以下代码,但是您会更好地知道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"
});
}
Also if string
in your code is a variable you need to change that because string
is reserved for the type. 另外,如果代码中的string
是变量,则需要更改它,因为string
是为该类型保留的。 In case you don't what to fix the type of doSomething
right now you can use the Function
type. 如果您现在还不能解决doSomething
的类型,则可以使用Function
类型。 Demo 演示版
For your updated question you need to write function performAction(doSomething: (stuff: someType) => void
Demo 对于更新的问题,您需要编写function performAction(doSomething: (stuff: someType) => void
Demo
You type doSomething as a function with no arguments: doSomething: () => void
. 您将doSomething键入为不带参数的函数: doSomething: () => void
。 Make it, dunno, doSomething: (arg: SomeInterface) => void
(SomeInterface being, for example, {name: string; id: string;}
). 将其设为dunno, doSomething: (arg: SomeInterface) => void
(SomeInterface例如为{name: string; id: string;}
)。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.