Nick
Nick

Reputation: 16576

How can I maintain type narrowing inside Array.find method?

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.

Is there a reason this type is losing its narrowing within the find method? What options do I have to successfully narrow this type?

TS2345 [ERROR]: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type '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
    );
  }
};

Upvotes: 1

Views: 313

Answers (1)

Eugene Karataev
Eugene Karataev

Reputation: 1971

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

Upvotes: 2

Related Questions