Within the code snippet below, I am encountering a typescript compilation error specifically in the Array.find method. Despite checking that `context.params.id` is not `undefined`, my type seems to lose its narrowing.
I'm puzzled as to why this type loses its narrowness within the find method. Are there any alternatives available to successfully narrow down this type?
Error: TS2345 - 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)
);
}
};