Issue
Suppose the following:
const data = [
{ id: '1' },
{ id: null },
{ id: '2' },
{ id: null },
{ id: '3' },
];
const result: string[] = data.map(({ id }) => id).filter(Boolean);
^^^^^^
// Type '(string | null)[]' is not assignable to type 'string[]'
I know I can add as string[]
at the end, but why is this happening, if the result of such an operation will obviously never yield an array with a null
element in it?
Solution
Typescript is not smart enough to understand what Boolean might be doing. It is doing strict checking, by looking at the possible types that can be returned from filter()
method which is (string | null)[]
If you use a type guard it will work:
const data = [
{ id: '1' },
{ id: null },
{ id: '2' },
{ id: null },
{ id: '3' },
];
const result: string[] = data.map(({ id }) => id).filter((id) : id is string => Boolean(id));
Answered By - Tushar Shahi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.