【发布时间】: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