最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

TypeScript not detecting type in filter() - Stack Overflow

programmeradmin5浏览0评论
 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
Add a comment  | 

2 Answers 2

Reset to default 1

Typescript 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.

发布评论

评论列表(0)

  1. 暂无评论