问题库 JavaScript / TypeScript how-to

TypeScript filter 后如何去掉 null 类型

快速答案

写类型谓词函数,让编译器知道过滤后的数组不含 null。

js
const values = list.filter((item): item is string => item !== null);

使用要点

  • TypeScript 只在编译期提供保护,接口返回值仍要做运行时校验。
  • 类型收窄写清楚以后,再把数据交给业务函数,减少后续的断言。

相关内容