我正在尝试将此doSomething函数传递给performAction,但是我遇到的错误是Expected 0 arguments, but got 1type 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);我是否为Typescript使用正确的语法?
2 回答

胡说叔叔
TA贡献1804条经验 获得超8个赞
该doSomething类型似乎不正确。在类型声明中-() => void它不接受任何参数,但是稍后您将参数传递给它。
对于这段代码,可以使用以下代码,但是您会更好地知道的参数及其类型应该是什么doSomething。如果您已经有了抽象的想法,则可能使用接口。
function performAction(doSomething: (stuff: { name: string, id: string }) => void) {
doSomething({
name: "foo",
id: "bar"
});
}
另外,如果string您的代码中有一个变量,则需要更改该变量,因为该变量string是为该类型保留的。如果您现在还不能解决该问题,doSomething可以使用该Function类型。
更新
对于更新的问题,您需要编写function performAction(doSomething: (stuff: someType) => void

互换的青春
TA贡献1797条经验 获得超6个赞
您将doSomething键入为不带参数的函数:doSomething: () => void
。将其设为dunno doSomething: (arg: SomeInterface) => void
(例如,SomeInterface是{name: string; id: string;}
)。
添加回答
举报
0/150
提交
取消