typescript - 在数组的过滤方法之后指定所需的类型
问题描述
我想在两个数组之间进行分隔。在一个数组中,对象没有特定值。另一方面,它应该有一个字符串。
interface Relation<T> {
href: URL;
notAlways: T;
}
// This response sometimes has a string or a null value in the 'notAlways' key.
const response: { relations: Relation<string | null>[] } = await request(paramUrl);
const doesNotHaveIt: Relation<null>[] = response.relations.filter(
(relation: Relation<string | null>) => !relation.notAlways,
);
// Error: Type 'Relation<string | null>' is not assignable to type 'Relation<null>
const doesHaveIt: Relation<string> = response.relations.filter(
(relation: Relation<string | null>) => relation.notAlways
);
// Error: Type 'Relation<string | null>' is not assignable to type 'Relation<string>'.
解决方案
您可以使谓词(传递给filter
)类型保护:
const doesNotHaveIt: Relation<null>[] = response.relations.filter(
(relation: Relation<string | null>): relation is Relation<null> => !relation.notAlways,
);
const doesHaveIt: Relation<string>[] = response.relations.filter(
(relation: Relation<string | null>): relation is Relation<string> => !!relation.notAlways
);
现在可以删除显式变量注释,因为它已正确推断:
const doesNotHaveIt = response.relations.filter(
(relation: Relation<string | null>): relation is Relation<null> => !relation.notAlways,
); // doesNotHaveIt is Relation<null>[]
推荐阅读
- python - 在 Pydub 和 Librosa 之间转换音频文件
- reactjs - 使用 useMemo 或 useCallback VS useRef 清空依赖项
- javascript - 从用户 Node.js 接收和处理数据
- visual-studio - 为什么包管理器控制台会提示我启用包还原修复?
- javascript - 查找总和为给定数量数组发行的最小数量的纸币和价值
- windows - 为什么连续调用 SetForegroundWindow 不起作用?
- java - 我应该使用哪种图形算法来找到通过所有给定目的地的最快路线?
- c - 了解 SISL 库中的原型/函数语法
- python-3.x - 你如何让 pytest 像 python 一样理解 python 模块?
- javascript - 在 vuejs 中,输入事件触发在列表中不起作用