如何使用打字稿键入此回调函数

时间:2020-11-05 19:00:43

标签: javascript typescript

在下面的代码中,我将调度功能键入为“ any”。我这样做是为了清除如果我没有键入它会得到的错误。

用Typescript打字的正确方法是什么?

$VAR1 = [
          1,
          2,
          3,
          undef,
          undef,
          4
        ];
$VAR1 = [
          1,
          2,
          3,
          4
        ];

1 个答案:

答案 0 :(得分:0)

您应为pingActionResult的退货指定接口,然后在dispatch的定义中使用该接口

例如,

interface PingActionResult
{
    field1: string;
    field2: string;
}

您的代码可能如下:

export function doThing() {
  console.log("works")
  return (dispatch:(result:PingActionResult) => void) => {  // any ?       
    fetch('https://whatever.com/some-api').then((response) => {
      return response.json()
    }).then((data) => {

      dispatch(pingApiAction(data))
    })
  };
}

// just for illustration
function pingApiAction(data:{}): PingActionResult{
    return {field1: "foo", field2: "bar"}
}