admin管理员组文章数量:1405516
const values: (string | null)[] = [];
const filtered = values.filter((v) => v !== null && v.trim() !== "");
filtered // still (string | null)[]
Why does TypeScript not detect the filtering of null values?
const values: (string | null)[] = [];
const filtered = values.filter((v) => v !== null && v.trim() !== "");
filtered // still (string | null)[]
Why does TypeScript not detect the filtering of null values?
Share Improve this question edited Mar 21 at 22:55 jonrsharpe 122k30 gold badges268 silver badges476 bronze badges asked Mar 21 at 22:21 AlexAlex 66.2k185 gold badges459 silver badges651 bronze badges 1- This question is similar to: Why can't my filter method narrow the type and eliminate the undefined and false from the array?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – jonrsharpe Commented Mar 21 at 22:55
2 Answers
Reset to default 1Typescript can't infer what your function is actually doing.
However, you can give it a predicate :
const filtered = values.filter((v): v is string => v !== null && v.trim() !== "");
const filtered = values.filter((v) => v !== null && v.trim() !== "");
Please observe below the return type of the callback passed into filter. This will get by hovering over the literal filter in the above statement. The callback returns the type (string | null). Therefore the resultant array is also typed accordingly. This is the reason for the undesired type (string | null)[].
(method) Array<string | null>.filter(predicate: (value: string | null, index: number, array: (string | null)[]) => unknown, thisArg?: any): (string | null)[] (+1 overload)
Solution: using a type predicate
The expression v is string included in the below statement asserts the return type of the callback as string. This can be checked again by hovering the literal filter. However, this kind of assertion is safe since the condition guards v !== null && v.trim() !== "" this assertion. This assertion effectively narrows the type from (string | null)[] to string[].
const filtered = values.filter((v) : *v is string* => v !== null && v.trim() !== "");
By hovering the literal filter
(method) Array<string | null>.filter<string>(predicate: (value: string | null, index: number, array: (string | null)[]) => value is string, thisArg?: any): string[] (+1 overload)
For more, please read Using type predicates.
本文标签: TypeScript not detecting type in filter()Stack Overflow
版权声明:本文标题:TypeScript not detecting type in filter() - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744331678a2600994.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论