如何在Array.find方法中保持类型缩小?

In the following code snippet, I'm receiving the following typescript compilation error within the Array.find method. I would expect that my type is narrowed given the if statement checking that context.params.id is not undefined.

这种类型在find方法中失去其缩小范围是否有原因?要成功缩小此类型,我必须采取什么选择?

TS2345 [ERROR]:类型为'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
    );
  }
};
评论
  • 木叶
    木叶 回复

    One option is to assign context.params.id to a new variable outside of find callback.

    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
        );
      }
    };