Issue
The following code
const s: string[] = ["x", "y", "z"].map(i => ["x"].find(t => t === i));
This causes an error "Type '(string | undefined)[]' is not assignable to type 'string[]'." as find
gives string | undefined
. So I was hoping adding a filter can fix that, like:
const s: string[] = ["x", "y", "z"].map(i => ["x"].find(t => t === i)).filter(i => i);
But this didn't work, why?
TS version 4.2.3
Solution
If you know for sure that the find
call here will never return undefined
, you can use an assertion with '!':
const s: string[] = ["x", "y", "z"].map(i => ["x"].find(t => t === i)!);
// ^
Otherwise you will have to write a guard:
function isDefinitelyAString(val: unknown): val is string {
return typeof val === "string";
}
const s: string[] = ["x", "y", "z"].map(i => ["x"].find(t => t === i)).filter(isDefinitelyAString);
You can also inline the guard like @jonrsharpe suggests:
const s: string[] = ["x", "y", "z"].map(i => ["x"].find(t => t === i)).filter((i): i is string => typeof i === "string");
Answered By - catgirlkelly
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.