【问题标题】:How can I maintain type narrowing inside Array.find method?如何在 Array.find 方法中保持类型缩小?
【发布时间】:2020-09-03 05:56:47
【问题描述】:

在以下代码 sn-p 中,我在 Array.find 方法中收到以下打字稿编译错误。鉴于if 语句检查context.params.id 不是undefined,我预计我的类型会缩小。

这种类型在 find 方法中失去缩小范围是否有原因?我有哪些选择可以成功缩小这种类型的范围?

TS2345 [错误]:'string | 类型的参数undefined' 不能分配给'string' 类型的参数。 类型“未定义”不可分配给类型“字符串”。

type Book = {
  id: number;
}

const books: Book[] = [];

type Context = {
  response: {
    body: any;
  },
  params?: {
    id?: string
  }
}

const handler = (context: Context) => {
  if (context.params && context.params.id) {
    context.response.body = books.find(
      (book) => book.id === parseInt(context.params.id) // Error
    );
  }
};

【问题讨论】:

    标签: typescript


    【解决方案1】:

    一种选择是将context.params.id 分配给find 回调之外的新变量。

    const handler = (context: Context) => {
      if (context.params && context.params.id) {
        const id = parseInt(context.params.id);
        context.response.body = books.find(
          (book) => book.id === id // OK
        );
      }
    };
    

    【讨论】:

    • 啊有趣。我喜欢这种方法。知道为什么在 find 方法中会丢失缩小范围吗?
    • 查找功能并没有丢失,它无处不在。 Typescript 无法确定该变量不会在空检查和稍后在某处使用它之间发生变化。即使您使用let 而不是const 执行let id = parseInt(context.params.id);,您也会得到相同的错误。我会在函数的开头做const id = context?.params?.id,并在 if 和 find 块中使用它。
    • @ritaj 使用 let 似乎没问题:typescriptlang.org/play?#code/…
    猜你喜欢
    • 2021-05-21
    • 2014-04-17
    • 2011-07-31
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 2022-10-02
    相关资源
    最近更新 更多